Monday, January 10, 2011

Database programming in Perl

Database programming in Perl shows how to connect to a mysql or oracle database or any 
other database and execute any sql statement in the connected database through a Perl 
program.

The following example shows connecting to a database and executing insert, update, 
select statement on a table of the connected database through the DBI module.

Following is the table structure with a record set, on which the following example 
is operating:

---------------------------------------------------------------
|Tablename: employee|                                         |
|-------------------------------------------------------------|
|emp_id(varchar(255))|employee_name(varchar(255))|age(integer)|
|--------------------|---------------------------|------------|
|001                 |James Dcosta               | 35         |
---------------------------------------------------------------

#!/usr/bin/perl

use DBI; # the module required for performing the database programming operations

$dbh=DBI->connect("dbi:mysql:db_name:server_name","db_username","db_password"); # establishing a data base connection by specifying the database driver (here dbi:mysql is used for connecting to a mysql database), database name, server ip or name of the server where the database is residing and then the database username and the database password respectively

$sth=$dbh->prepare("insert into employee(emp_id,employee_name,age) value(?,?,?)"); # preparing the insert statement with place holders (?), for emp_id, employee_name, age and storing it in a statement handle 

$sth->execute("002","Michael Jonson",40); # executing the statement by passing respective values for the place holders, here employee id, employee name and age 

print "Record Inserted\n";

$sth=$dbh->prepare("select emp_id,employee_name,age from employee where emp_id=?"); # preparing the select statement with place holders (?) for emp_id, employee_name, age and storing it in a statement handle 

$sth->execute("002"); # executing the statement by passing respective values for the place holders, here employee id 

while(@data=$sth->fetchrow_array()) # fetching one row at a time from the table and storing it in an array
{
 print "$data[0] -- $data[1] -- $data[2]\n"; # displaying the fetched records on the screen, the first element of the array holds the first column data and then the second element of the array holds the second column data from the row respectively, etc
}

$sth->finish(); # indicates that no more data will be fetched from this statement handle

$sth=$dbh->prepare("update employee set age=? where emp_id=?"); # preparing the update statement with place holders (?), for updating age for a given employee id

$sth->execute(45,"002"); # executing the statement by passing respective values for the place holders, here new value for age and employee id of the employee whose age is to be modified 

print "Record Modified\n";

# displaying all rows from the table

$sth=$dbh->prepare("select emp_id,employee_name,age from employee");

$sth->execute();

while(@data=$sth->fetchrow_array())
{
 print "$data[0] -- $data[1] -- $data[2]\n";
}

$sth->finish();

Output:
-------
002 -- Michael Jonson -- 40
001 -- James Dcosta -- 35
002 -- Michael Jonson -- 45

Sunday, January 9, 2011

Working with session variables

The following "set_session.pl" program shows how to set values in session variables:
#!/usr/bin/perl

use CGI;

use CGI::Session; # module required for using session variables 

my $cgi = new CGI;

# object initialized for accesing session variables
my $session = CGI::Session->new();

# setting values in user defined session variables
$session->param('my_name', 'James');
$session->param('my_age', '36');

# defining a cookie with the name "session_id" and storing the current session id as it's value, to be used later for accessing the values stored in the current session variables
my $cookie = CGI::Cookie->new( -name => "session_id", -value => $session->id );

# setting the cookie
print $cgi->header( -cookie =>  $cookie  );

print "Values stored in the session.";

The following "get_session.pl" program will read the values stored in the session variable set in the earlier program:
#!/usr/bin/perl

use CGI;

use CGI::Session;

my $cgi = new CGI;

print $cgi->header();

# retrieving the session id stored in the "session_id" cookie for accessing the earlier set session variables
my $session_id = $cgi->cookie("session_id");

# object initialized for accesing session variables from the passed session id
my $session = CGI::Session->new($session_id);

# fetching the values stored in session variables
my $name = $session->param('my_name');
my $age = $session->param('my_age');

print "My name is $name and I am $age years old.";


Output:
-------
On calling the "set_session.pl" program from browser, it will set an user defined name and age in session variables named 'my_name' and 'my_age' respectively to be accessed by other programs in the current session, the session id of the current session is stored in a cookie named "session_id" and then on calling the "get_session.pl" program from browser, it will fetch the session id stored in the cookie named "session_id" for accessing the session variables associated with id.

Working with cookies in Perl

The following "set_cookie.pl" program shows how to set cookies in perl:
#!/usr/bin/perl

use CGI; 

my $cgi = new CGI;

# creating cookies by specifying name and value for the cookie items with lifespan of the cookies set to 1 hour  

my $cookie_1 = $cgi->cookie( -name => 'friend_name',  -value => 'James Dcosta', -expires => '+1h'); 

my $cookie_2 = $cgi->cookie( -name => 'friend_age', -value => '36', -expires => '+1h');

# setting the cookies via response header 
print $cgi->header( -cookie => [$cookie_1, $cookie_2] );

print "Cookie Set";

The following "read_cookie.pl" program will read the cookie values set in the earlier program:
#!/usr/bin/perl

use CGI; 

my $cgi = new CGI;

print $cgi->header();

# reading the cookie values via CGI object

my $friend_name = $cgi->cookie('friend_name');

my $friend_age = $cgi->cookie('friend_age');

print "Reading values from cookies 
"; print "Friend Name: ".$friend_name."
"; print "Friend Age: ".$friend_age."
";

Output:
-------
On calling the "set_cookie.pl" program from browser, it will set friend name and age in cookies named 'friend_name' and 'friend_age' respectively and then on calling the "read_cookie.pl" program from browser, it will read the cookies named 'friend_name' and 'friend_age' set earlier and display on the screen.

Thursday, January 6, 2011

Reading command line arguments with @ARGV array in Perl


@ARGV is a special array in Perl, it holds the arguments passed to the program 
as each element of the array. Therefore $ARGV[0] contains the first argument and 
$ARGV[1] contains the second argument etc.
Following is an example of accepting the name and age of the end user as command 
line arguments and displaying the same as a well formed sentence:

#!/usr/bin/perl
#---------------------#
#  PROGRAM:  test_argv.pl  #
#---------------------#

print "My name is $ARGV[0] and I am $ARGV[1] years old\n";

Running the program from command line:
--------------------------------------
perl test_argv.pl James 33

Output:
-------
My name is James and I am 33 years old

STDIN and STDOUT filehandles in Perl

STDIN is responsible for accepting data from the standard input(e.g: keyboard)
and STDOUT is responsible for transmitting data to standard output(e.g: screen).

#!/usr/bin/perl

print "Enter your name and hit enter:";
chomp($name=<stdin>); # accepting data for name from the end user and storing it in a variable without the new line

print "Enter your age and hit enter:";
chomp($age=<stdin>); # accepting data for age from the end user and storing it in a variable without the new line

print STDOUT "your name is $name and you are $age years old\n"; # STDOUT is optional, as the standard output is screen/ monitor by default

Dynamically populating an array in PERL

Dynamically populating array elements in an array respective to it's index position. 

#!/usr/bin/perl

my @arr;

for (my $i = 0; $i < 55; $i++) {
 $arr[$i] = 'I am element number '.$i;
}

print "Value at Index 0 of Array = ".$arr[0]."\n";
print "Value at Index 1 of Array = ".$arr[1]."\n";
print "Value at Index 2 of Array = ".$arr[2]."\n";
print "Value at Index 3 of Array = ".$arr[3]."\n";
print "Value at Index 4 of Array = ".$arr[4]."\n";


Output:
-------
Value at Index 0 of Array = I am element number 0
Value at Index 1 of Array = I am element number 1
Value at Index 2 of Array = I am element number 2
Value at Index 3 of Array = I am element number 3
Value at Index 4 of Array = I am element number 4


File handling in Perl


The following example shows how to write few lines in a file named "test.txt" 
in the working directory through a Perl script.
After writing to the file, "test.txt" should contain the following:
-------------------
|Name:James Dcosta|
|Age:32           |
|Gender:Male      |
-------------------


#!/usr/bin/perl

print "content-type: text/html \n\n"; 

open(FL,">./test.txt"); # Opening the file in write mode. FL here represents the file handle required and can be any non keyword text

flock(FL,2); # Locking the file for writing

print FL "Name:James Dcosta\n"; # Writing the first line in the file followed by a line break at the end

print FL "Age:32\n"; # Writing the second line in the file followed by a line break

print FL "Gender:Male\n"; # Writing the third line in the file followed by a line break

flock(FL,8); # Releasing the lock from the file

close(FL); # closing the file after writing
After executing the script in the example above and few lines have been written 
in "text.txt" file, the following example shows how to read all the lines from 
the file: 

#!/usr/bin/perl

print "content-type: text/html \n\n"; 

open(FL,"<./test.txt"); # Opening the file in read mode. FL here represents the file handle required and can be any non keyword text

flock(FL,2); # Locking the file for reading

while (!eof(FL)) { # iterating the loop till the end of the file is reached
 chomp($rec=); # fetches the line the file handle is pointing at currently
 print "$rec\n";
}

flock(FL,8); # Releasing the lock from the file

close(FL); # closing the file after writing

Output:
-------------------
|Name:James Dcosta|
|Age:32           |
|Gender:Male      |
-------------------

File opening modes/ entities:
-----------------------------
< read mode
> create and write mode
>> create and append mode
+< read and update mode
+> read and write mode
+>> read and append mode

Advanced sorting of normal arrays, hash/ associative arrays in Perl


The following example shows all possible types of sorting in a normal array and also 
in a hash/ associative array through Perl. 

All The possible types of sorting are as follows :

1) Normal arrays = 2 types (ASCII wise sorting, numerical wise/ alphabetical wise 
sorting) X 2 ways (ascending/ normal order, descending order)

Total we have 4 alternatives for sorting a normal array. 

2) Hash/ Associative arrays:

 i) Sorting on the basis of keys = 2 types (ASCII wise sorting, numerical wise/ alphabetical wise sorting) X 2 ways (ascending/ normal order, descending order)
 
 Total we have 4 alternatives for sorting a hash/ associative arrays based on keys.

 ii) Sorting on the basis of values = 1 type (numerical wise/ alphabetical wise sorting) X 2 ways (ascending/ normal order, descending order)
 
 Total we have 2 alternatives for sorting a hash/ associative arrays based on values.


#!/usr/bin/perl

print "content-type: text/html \n\n";

###### sorting of an array with numeric values ########

@nums=(1,5,4,6,3,7,2,8,10,9);

print "Unsorted numbers from array: @nums\n";

@sorted_nums=sort(@nums); # ASCII wise sorting of normal array and storing the sorted result in another array

print "ASCII wise sorted numbers from array: @sorted_nums\n";

@sorted_nums=sort { $a <=> $b } @nums; # Numeric wise sorting of normal array and storing the sorted result in another array

print "Numeric wise sorted numbers from array: @sorted_nums\n";

@sorted_nums=sort { $b <=> $a } @nums; # Numeric wise sorting of normal array in reverse order and storing the sorted result in another array

print "Numeric wise sorted numbers in reverse order from array: @sorted_nums\n";


###### sorting of an array with character values ########

@chars=("B","a","d","C","E","f");

print "Unsorted characters from array: @chars\n";

@sorted_chars=sort(@chars); # ASCII wise sorting of normal array and storing the sorted result in another array

print "ASCII wise sorted characters from array: @sorted_chars\n";

@sorted_chars=sort { lc($a) cmp lc($b) } @chars; # Alphabet wise sorting of normal array and storing the sorted result in another array

print "Alphabetical wise sorted characters from array: @sorted_chars\n";

@sorted_chars=sort { lc($b) cmp lc($a) } @chars; # Alphabet wise sorting of normal array in reverse order and storing the sorted result in another array

print "Alphabetical wise sorted characters in reverse order from array: @sorted_chars\n";


###### sorting of hash/ associative arrays based on keys ########

%num_hash=(
 1 => "one",
 2 => "two",
 3 => "three",
 4 => "four",
 5 => "five",
 6 => "six",
 7 => "seven",
 8 => "eight",
 9 => "nine",
 10 => "ten",
);

print "\n-------------------------------------------\n";

foreach $key (sort keys%num_hash) # ASCII wise sorting of keys in hash/ associative array and displaying the sorted result on screen
{
 print "ASCII wise sorted numeric keys from hash: key=$key value=$num_hash{$key}\n";
}

print "\n-------------------------------------------\n";

foreach $key (reverse sort keys%num_hash) # ASCII wise sorting of keys in hash/ associative array in reverse order and displaying the sorted result on screen
{
 print "ASCII wise sorted numeric keys in reverse order from hash: key=$key value=$num_hash{$key}\n";
}

print "\n-------------------------------------------\n";

foreach $key (sort { $a <=> $b } keys%num_hash) # Numeric wise sorting of keys in hash/ associative array and displaying the sorted result on screen
{
 print "Numeric wise sorted numeric keys from hash: key=$key value=$num_hash{$key}\n";
}

print "\n-------------------------------------------\n";

foreach $key (sort { $b <=> $a } keys%num_hash) # Numeric wise sorting of keys in hash/ associative array in reverse order and displaying the sorted result on screen
{
 print "Numeric wise sorted numeric keys in reverse order from hash: key=$key value=$num_hash{$key}\n";
}


%char_hash=(
 "B" => "ball",
 "a" => "apple",
 "d" => "doll",
 "C" => "cat",
 "E" => "elephant",
 "f" => "fox",
);

print "\n-------------------------------------------\n";

foreach $key (sort keys%char_hash) # ASCII wise sorting of keys in hash/ associative array and displaying the sorted result on screen
{
 print "ASCII wise sorted character keys from hash: key=$key value=$char_hash{$key}\n";
}

print "\n-------------------------------------------\n";

foreach $key (reverse sort keys%char_hash) # ASCII wise sorting of keys in hash/ associative array in reverse order and displaying the sorted result on screen
{
 print "ASCII wise sorted character keys in reverse order from hash: key=$key value=$char_hash{$key}\n";
}

print "\n-------------------------------------------\n";

foreach $key (sort { lc($a) cmp lc($b) } keys%char_hash) # Alphabet wise sorting of keys in hash/ associative array and displaying the sorted result on screen
{
 print "Alplabetical wise sorted character keys from hash: key=$key value=$char_hash{$key}\n";
}

print "\n-------------------------------------------\n";

foreach $key (sort { lc($b) cmp lc($a) } keys%char_hash) # Alphabet wise sorting of keys in hash/ associative array in reverse order and displaying the sorted result on screen
{
 print "Alplabetical wise sorted character keys in reverse order from hash: key=$key value=$char_hash{$key}\n";
}


###### sorting of hash/ associative arrays based on values ########

%num_hash=(
 "one",1,
 "two",2,
 "three",3,
 "four",4,
 "five",5,
 "six",6,
 "seven",7,
 "eight",8,
 "nine",9,
 "ten",10,
);

print "\n-------------------------------------------\n";

foreach $key (sort { $num_hash{$a} <=> $num_hash{$b} } keys%num_hash) # Numeric wise sorting of values in hash/ associative array and displaying the sorted result on screen
{
 print "Numeric wise sorted numeric values from hash: key=$key value=$num_hash{$key}\n";
}

print "\n-------------------------------------------\n";

foreach $key (sort { $num_hash{$b} <=> $num_hash{$a} } keys%num_hash) # Numeric wise sorting of values in hash/ associative array in reverse order and displaying the sorted result on screen
{
 print "Numeric wise sorted numeric values in reverse order from hash: key=$key value=$num_hash{$key}\n";
}


%char_hash=(
 "a" => "Ball",
 "b" => "apple",
 "c" => "Cat",
 "d" => "doll",
 "e" => "Elephant",
 "f" => "fox",
);

print "\n-------------------------------------------\n";

foreach $key (sort { lc($char_hash{$a}) cmp lc($char_hash{$b}) } keys%char_hash) # Alphabet wise sorting of values in hash/ associative array and displaying the sorted result on screen
{
 print "Alplabetical wise sorted character values from hash: key=$key value=$char_hash{$key}\n";
}

print "\n-------------------------------------------\n";

foreach $key (sort { lc($char_hash{$b}) cmp lc($char_hash{$a}) } keys%char_hash) # Alphabet wise sorting of values in hash/ associative array in reverse order and displaying the sorted result on screen
{
 print "Alplabetical wise sorted character values in reverse order from hash: key=$key value=$char_hash{$key}\n";
}

Output:
-------
Unsorted numbers from array: 1 5 4 6 3 7 2 8 10 9
ASCII wise sorted numbers from array: 1 10 2 3 4 5 6 7 8 9
Numeric wise sorted numbers from array: 1 2 3 4 5 6 7 8 9 10
Numeric wise sorted numbers in reverse order from array: 10 9 8 7 6 5 4 3 2 1
Unsorted characters from array: B a d C E f
ASCII wise sorted characters from array: B C E a d f
Alphabetical wise sorted characters from array: a B C d E f
Alphabetical wise sorted characters in reverse order from array: f E d C B a

-------------------------------------------
ASCII wise sorted numeric keys from hash: key=1 value=one
ASCII wise sorted numeric keys from hash: key=10 value=ten
ASCII wise sorted numeric keys from hash: key=2 value=two
ASCII wise sorted numeric keys from hash: key=3 value=three
ASCII wise sorted numeric keys from hash: key=4 value=four
ASCII wise sorted numeric keys from hash: key=5 value=five
ASCII wise sorted numeric keys from hash: key=6 value=six
ASCII wise sorted numeric keys from hash: key=7 value=seven
ASCII wise sorted numeric keys from hash: key=8 value=eight
ASCII wise sorted numeric keys from hash: key=9 value=nine

-------------------------------------------
ASCII wise sorted numeric keys in reverse order from hash: key=9 value=nine
ASCII wise sorted numeric keys in reverse order from hash: key=8 value=eight
ASCII wise sorted numeric keys in reverse order from hash: key=7 value=seven
ASCII wise sorted numeric keys in reverse order from hash: key=6 value=six
ASCII wise sorted numeric keys in reverse order from hash: key=5 value=five
ASCII wise sorted numeric keys in reverse order from hash: key=4 value=four
ASCII wise sorted numeric keys in reverse order from hash: key=3 value=three
ASCII wise sorted numeric keys in reverse order from hash: key=2 value=two
ASCII wise sorted numeric keys in reverse order from hash: key=10 value=ten
ASCII wise sorted numeric keys in reverse order from hash: key=1 value=one

-------------------------------------------
Numeric wise sorted numeric keys from hash: key=1 value=one
Numeric wise sorted numeric keys from hash: key=2 value=two
Numeric wise sorted numeric keys from hash: key=3 value=three
Numeric wise sorted numeric keys from hash: key=4 value=four
Numeric wise sorted numeric keys from hash: key=5 value=five
Numeric wise sorted numeric keys from hash: key=6 value=six
Numeric wise sorted numeric keys from hash: key=7 value=seven
Numeric wise sorted numeric keys from hash: key=8 value=eight
Numeric wise sorted numeric keys from hash: key=9 value=nine
Numeric wise sorted numeric keys from hash: key=10 value=ten

-------------------------------------------
Numeric wise sorted numeric keys in reverse order from hash: key=10 value=ten
Numeric wise sorted numeric keys in reverse order from hash: key=9 value=nine
Numeric wise sorted numeric keys in reverse order from hash: key=8 value=eight
Numeric wise sorted numeric keys in reverse order from hash: key=7 value=seven
Numeric wise sorted numeric keys in reverse order from hash: key=6 value=six
Numeric wise sorted numeric keys in reverse order from hash: key=5 value=five
Numeric wise sorted numeric keys in reverse order from hash: key=4 value=four
Numeric wise sorted numeric keys in reverse order from hash: key=3 value=three
Numeric wise sorted numeric keys in reverse order from hash: key=2 value=two
Numeric wise sorted numeric keys in reverse order from hash: key=1 value=one

-------------------------------------------
ASCII wise sorted character keys from hash: key=B value=ball
ASCII wise sorted character keys from hash: key=C value=cat
ASCII wise sorted character keys from hash: key=E value=elephant
ASCII wise sorted character keys from hash: key=a value=apple
ASCII wise sorted character keys from hash: key=d value=doll
ASCII wise sorted character keys from hash: key=f value=fox

-------------------------------------------
ASCII wise sorted character keys in reverse order from hash: key=f value=fox
ASCII wise sorted character keys in reverse order from hash: key=d value=doll
ASCII wise sorted character keys in reverse order from hash: key=a value=apple
ASCII wise sorted character keys in reverse order from hash: key=E value=elephant
ASCII wise sorted character keys in reverse order from hash: key=C value=cat
ASCII wise sorted character keys in reverse order from hash: key=B value=ball

-------------------------------------------
Alplabetical wise sorted character keys from hash: key=a value=apple
Alplabetical wise sorted character keys from hash: key=B value=ball
Alplabetical wise sorted character keys from hash: key=C value=cat
Alplabetical wise sorted character keys from hash: key=d value=doll
Alplabetical wise sorted character keys from hash: key=E value=elephant
Alplabetical wise sorted character keys from hash: key=f value=fox

-------------------------------------------
Alplabetical wise sorted character keys in reverse order from hash: key=f value=fox
Alplabetical wise sorted character keys in reverse order from hash: key=E value=elephant
Alplabetical wise sorted character keys in reverse order from hash: key=d value=doll
Alplabetical wise sorted character keys in reverse order from hash: key=C value=cat
Alplabetical wise sorted character keys in reverse order from hash: key=B value=ball
Alplabetical wise sorted character keys in reverse order from hash: key=a value=apple

-------------------------------------------
Numeric wise sorted numeric values from hash: key=one value=1
Numeric wise sorted numeric values from hash: key=two value=2
Numeric wise sorted numeric values from hash: key=three value=3
Numeric wise sorted numeric values from hash: key=four value=4
Numeric wise sorted numeric values from hash: key=five value=5
Numeric wise sorted numeric values from hash: key=six value=6
Numeric wise sorted numeric values from hash: key=seven value=7
Numeric wise sorted numeric values from hash: key=eight value=8
Numeric wise sorted numeric values from hash: key=nine value=9
Numeric wise sorted numeric values from hash: key=ten value=10

-------------------------------------------
Numeric wise sorted numeric values in reverse order from hash: key=ten value=10
Numeric wise sorted numeric values in reverse order from hash: key=nine value=9
Numeric wise sorted numeric values in reverse order from hash: key=eight value=8
Numeric wise sorted numeric values in reverse order from hash: key=seven value=7
Numeric wise sorted numeric values in reverse order from hash: key=six value=6
Numeric wise sorted numeric values in reverse order from hash: key=five value=5
Numeric wise sorted numeric values in reverse order from hash: key=four value=4
Numeric wise sorted numeric values in reverse order from hash: key=three value=3
Numeric wise sorted numeric values in reverse order from hash: key=two value=2
Numeric wise sorted numeric values in reverse order from hash: key=one value=1

-------------------------------------------
Alplabetical wise sorted character values from hash: key=b value=apple
Alplabetical wise sorted character values from hash: key=a value=Ball
Alplabetical wise sorted character values from hash: key=c value=Cat
Alplabetical wise sorted character values from hash: key=d value=doll
Alplabetical wise sorted character values from hash: key=e value=Elephant
Alplabetical wise sorted character values from hash: key=f value=fox

-------------------------------------------
Alplabetical wise sorted character values in reverse order from hash: key=f value=fox
Alplabetical wise sorted character values in reverse order from hash: key=e value=Elephant
Alplabetical wise sorted character values in reverse order from hash: key=d value=doll
Alplabetical wise sorted character values in reverse order from hash: key=c value=Cat
Alplabetical wise sorted character values in reverse order from hash: key=a value=Ball
Alplabetical wise sorted character values in reverse order from hash: key=b value=apple

Using map and grep in Perl

Using map and grep in Perl

map and grep are very useful functions in Perl, they help to reduce longer lines of 
codes in a script.

map function evaluates a block of code on each element of a given list and returns 
the result of each such evaluation. 

grep function evaluates an expression on each element of a given list and returns 
those elements for which the expression evaluated to true. 

#!/usr/bin/perl

print "content-type: text/html \n\n";

@cities = ("Kolkata","Mumbai","Hydrebad","Kohima","Delhi");

%cities_hash = map {$_ => 1} @cities; # storing the list of cities from @cities array in a new hash, $_ here represents individual element in @cities array

foreach $city (keys%cities_hash) {
 print "$city\n";
}

@cities_with_k = grep {/^k/i} @cities; # filtering cities starting with k and storing them in a new array

print "Cities starting with K: @cities_with_k\n";

Output:
-------
Delhi
Kohima
Mumbai
Kolkata
Hydrebad
Cities starting with K: Kolkata Kohima

Loops in Perl

Perl has four main types of loop i.e: while, until, for, foreach.
Each of the loops have their own characteristcs, which are described in the 
following example: 

#!/usr/bin/perl

print "content-type: text/html \n\n"; 

$i=1;
while ($i<=3) # iterates till the expression is true 
{
 print "while $i\n";
 $i=$i+1;
}

$i=1;
do # the block executes at least once and then tests the expression for next iteration 
{ 
 print "do while $i\n";
 $i=$i+1; 
} while ($i<=0); # iterates till the expression is true 

$i=3;
until ($i<1) # iterates till the expression is false 
{
 print "until $i\n";
 $i=$i-1;
}

$i=3;
do # the block executes at least once and then tests the expression for next iteration 
{ 
 print "do until $i\n";
 $i=$i-1; 
} until ($i<=3); # iterates till the expression is false 

@array=(1,2,3,4,5); # an array of integers

for ($i=0; $i<$#array; $i++) # iterates till the expression is true 
{
 print "for $array[$i]\n";
}

foreach $values (@array) # iterates till the end of the supplied list is reached
{
 print "foreach $values\n";
}

Output:
-------
while 1
while 2
while 3
do while 1
until 3
until 2
until 1
do until 3
for 1
for 2
for 3
for 4
for 5
foreach 1
foreach 2
foreach 3
foreach 4
foreach 5

Wednesday, January 5, 2011

if and unless conditional statements in Perl

The following example finds the greatest number amongst three given numbers, 
finds the greater number between two given numbers and also checks for the 
equality of two string values

#!/usr/bin/perl

print "content-type: text/html \n\n"; 

$a=1;
$b=2;
$c=3;

if($a > $b && $a > c) # executes if the expression is true
{
 print "$a is greatest\n";
}
elsif($b > $a && $b > $c) # executes if the expression is true
{
 print "$b is greatest\n";
}
elsif($a == $b && $a == $c) # executes if the expression is true
{
 print "all are equal\n";
}
else
{
 print "$c is greatest\n";
}

unless ($b <= $a) # executes if the expression is false
{
 print "$b is greater than $a\n";
}

$string_1="your name";
$string_2="yours name";

if($string_1 eq $string_2) # executes if the expression is true
{
 print "both the strings are same\n"; 
}
else
{
 print "both the strings are not same\n"; 
}

Output:
-------
3 is greatest
2 is greater than 1
both the strings are not same

Numeric Comparison Operators:
-----------------------------
== equal to
!= not equal to
> greater than
< lesser than
>= greater or equal to
<= lesser or equal to

String/ Character Comparison Operators:
-----------------------------
eq => equal to
ne => not equal to
gt => greater than
lt => lesser than

Monday, January 3, 2011

Sorting of an array in Perl

#!/usr/bin/perl

print "content-type: text/html \n\n";

@arr=qw (a c e f d h g i b j);

@arr2=sort(@arr); # default sorting in ascending order
print "Ascending: @arr2\n";

@arr2=reverse sort(@arr); # sorting in descending order
print "Descending: @arr2\n";

Output:
-------
Ascending: a b c d e f g h i j
Descending: j i h g f e d c b a

Saturday, January 1, 2011

splice() function in Perl

splice() function in Perl is responsible for replacing/ removing elements from 
an array by specifying the element subscript positions

#!/usr/bin/perl

print "content-type:text/html\n\n";

@browser = ("NS", "IE", "Opera");

splice(@browser, 1, 2); # removes elements from position 1 and 2 of the array
print "@browser\n";

@browser = ("NS", "IE", "Opera");
splice(@browser, 1, 2, "NeoPlanet", "Mosaic"); # replaces elements present in position 1 and 2 of the array with the respective values specified thereof
print "@browser\n";

Output:
-------
NS
NS NeoPlanet Mosaic

Monday, December 27, 2010

chomp(), chop(), substr(), length(), uc(), ucfirst(), lcfirst() functions in Perl

These are some inbuilt functions in Perl which are commonly used in the course 
of programing

#!/usr/bin/perl
print "content-type: text/html \n\n";

$str="hello world\n";

chomp($str);  # removes the new line character from the end of a string
print $str."Intrasoft\n";

chop($str); # removes the last character from the end of a string
print $str."\n";

$temp_str=substr($str,4,3); # returns the characters starting from the 5th position of the string to 3 characters from the 5th position of the string
print $temp_str."\n";

$temp_str=substr($str,4); # returns the characters starting from the 5th position of the string till the end of the string
print $temp_str."\n";

$str_len=length($str); # return the length of the string in number of charaters
print $str_len."\n";

$temp_str=uc($str); # converts and returns the string in upper case
print $temp_str."\n";

$temp_str=ucfirst($str); # converts and returns the string with it's 1st character in upper case
print $temp_str."\n";

$temp_str=lc($str); # converts and returns the string in lower case
print $temp_str."\n";

$temp_str=lcfirst($str); # converts and returns the string with it's 1st character in lower case
print $temp_str."\n";

Output:
-------
hello worldIntrasoft
hello worl
o w
o worl
10
HELLO WORL
Hello worl
hello worl
hello worl

Sunday, December 26, 2010

join() function in Perl

join() function in Perl is responsible for joining all the elements in an array
into a single string.

#!/usr/bin/perl

print "content-type: text/html \n\n";

@array = ("David","Larry","Roger","Ken","Michael","Tom");
$astring = join(",",@array);
print $astring."\n";

@array2 = qw(Pizza Steak Chicken Burgers);
$string = join("\n",@array2);
print $string;

Output:
-------
David,Larry,Roger,Ken,Michael,Tom
Pizza
Steak
Chicken
Burgers

Friday, December 24, 2010

scalar() function in Perl

scalar() is an inbuilt function of Perl responsible for returning the number of
elements present in the array passed to the function

#!/usr/bin/perl

print "content-type: text/html \n\n";

@nums = (1 .. 20); # assigning 1 to 20 in the array sequentially as separate elements
@alpha = ("a" .. "z"); # assigning a to z in the array sequentially as separate elements
$numofnums = @nums;

print "@nums\n";

print "@alpha\n";

print "There are $numofnums numerical elements";

print "There are ".scalar(@alpha)." letters in the alphabet!";

Output:
-------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
a b c d e f g h i j k l m n o p q r s t u v w x y z
There are 20 numerical elements
There are 26 letters in the alphabet!

Wednesday, December 22, 2010

Hash/ Associative arrays in Perl

Hash/ Associative arrays in Perl are also responsible for storing multiple 
elements together in one variable, as a key value pair.

#!/usr/bin/perl

print "content-type: text/html \n\n"; 

%country_capital_hash=(
'india' => 'New Delhi',
'china' => 'beiging'
);

print "Capital of India is $country_capital_hash{'india'}\n";

Output:
-------
Capital of India is New Delhi

Tuesday, December 21, 2010

Some more examples of Perl arrays

Individual element in an array can be referred with their subscript position in
the array. The first element in an array is always at position "0". An array 
structure is always circular.

#!/usr/bin/perl

print "content-type: text/html \n\n";  

@array = ("Quarter","Dime","Nickel");

print "@array\n";

print "$array[0]\n"; # Prints the first element in the array

print "$array[1]\n"; # Prints the second element in the array

print "$array[2]\n"; # Prints the third element in the array

print "$array[-1]\n"; # Prints the last element in the array

print "$array[-2]\n"; # Prints second to last element in the array

Output:
-------
Quarter Dime Nickel
Quarter
Dime
Nickel
Nickel
Dime

Monday, December 20, 2010

Array variables in Perl

Arrays are list type variables, they contain any number of elements desired. 

#!/usr/bin/perl

print “content-type: text/html \n\n";

@days = ("Monday", "Tuesday", "Wednesday");
@months = ("April", "May", "June");

print "@days\n";
print "\n"; # displaying new line on the screen
print "@months\n";

Output:
-------
Monday Tuesday Wednesday
April May June

Saturday, December 18, 2010

Operators & Assignment


#!/usr/bin/perl

print "content-type: text/html \n\n";

$x = 81;                          
$add = $x + 9;    # calculating addition value
$sub = $x - 9; # calculating minus value
$mul = $x * 10; # calculating multiplication value
$div = $x / 9; # calculating division value
$exp = $x ** 5; # calculating exponential value
$mod = $x % 85; # calculating modulas/ remainder value

print "$x plus 9 is $add";

print "$x minus 9 is $sub";

print "$x times 10 is $mul";

print "$x divided by 9 is $div";

print "$x to the 5th is $exp";

print "$x divided by 85 has a remainder of $mod";


Output :
--------
81 plus 9 is 90
81 minus 9 is 72
81 times 10 is 810
81 divided by 9 is 9
81 to the 5th is 3486784401
81 divided by 79 has a remainder of 2

Wednesday, December 15, 2010

Concatenation of strings

Concatenation of strings here means, merging  two or more variables holding 
string type data into one variable side by side.

#!/usr/bin/perl

print "content-type:text/html\n\n";

$str1="Hello";

$str2="World";

$str=$str1." ".$str2;

print $str;

Output:
-------
Hello World

Friday, December 10, 2010

Scalar variables

Scalar variables are simple variables containing only one element. An element
can be either an entire string, a number, or a reference. Strings may contain any
symbol, letter, or number. Numbers may contain exponents, integers, or decimal
values.

#!/usr/bin/perl

print “content-type: text/html \n\n";

$mystring = "Hello, World";
$myescapechar = "Welcome to Joe\'s";
$myinteger = "5";
$myinteger2 = "-5";
$mypi = "3.14159";

print $mystring;

print $myescapechar;

print $myinteger;

print $myinteger2;

print $mypi;

Output:
-------
Hello, World!
Welcome to Joe's
5
-5
3.1459

Friday, December 3, 2010

Displaying "Hello World" on the screen


#!/usr/bin/perl

print "content-type:text/html\n\n"; #specifies the response header for the Perl script

print "Hello World"; #Displays Hello World on the screen

Output:
-------
Hello World

Thursday, December 2, 2010

How to use Perl for writing a program and executing it?

Following are the numbered steps, that are needed to be followed for successful 
execution of a Perl script :

1) Install Perl in your UNIX/ LINUX system ( get it from http://www.perl.org/get.html ),
if not already installed.

2) Open any text editor in your system and write the codes for the script.

3) Save the script by specifying a file name  with a ".pl" or ".cgi" extension 
( optional ). e.g: test.pl

4) In the above step the script file created can be stored in any location of your 
system but try to save the file in the "cgi-bin" folder ( which is automatically 
created at the time of Perl installation ) because then the script can also be run 
as a CGI script if requirement arises.

5) Finally the script can be executed as follows:
  • Go to the command prompt of your system and change directory to the location where the script is stored.
  • Type "perl file name.pl" and then hit enter. e.g: perl test.pl
  • or if running a CGI script, then open any web browser and type "http://server_address/cgi-bin/" and then hit enter. e.g: http://localhost/cgi-bin/test.pl

Wednesday, December 1, 2010

What is Perl?

Perl stands for (Practical Extraction and Report Language) and is also a popular CGI 
programming language. Perl makes our life easy in writing complex report processing 
programs, the main strength of the programing language is it's text processing 
facilities and easy manipulation of text files, it is also popularly used for server 
side scripting via CGI method.