Friday, February 25, 2011

Regular expressions in Perl

Regular expressions are a syntax that helps in string type data manipulation, like pattern matching, string selections and string replacements.

Following is a simple example showing how to use regular expressions in Perl.

#!/usr/bin/perl

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

$string = "Hello And Good Morning James";

if ($string =~ m/Good/) # m before the first slash is the "match" operator, returns true if "Good" is found in the string.
{
 print "Good found in $string\n";
}

if ($string =~ m/^Hello/) # ^ after the first slash signifies matching to be done from the starting of the string, returns true if "Hello" is found at the starting of the string. 
{
 print "Hello found at the starting of $string\n";
}

if ($string =~ m/James$/) # $ before the last slash signifies matching to be done from the ending of the string, returns true if "James" is found at the end of the string. 
{
 print "James found at the end of $string\n";
}

if ($string =~ m/good/i) # i after the last slash signifies matching to be done ignoring the case, returns true if "good" in any case (upper, lower, toggle, sentence) is found in the string.
{
 print "good found in $string\n";
}

$string =~ m/Hello And(.*)James/; # (.*) in the pattern returns the missing/ unknown characters from the string in a special variable

$fetched_string = $1; # $1 here represents the special variable holding the returned missing/ unknown characters from the previous regular expression.
print "$fetched_string\n";

$string =~ s/Morning/Evening/; # s before first slash is "substitute" operator, here if "Morning" is present in the string it will be replaced with "Evening". 
print "$string\n";

Output:
-------
Good found in Hello And Good Morning James
Hello found at the starting of Hello And Good Morning James
James found at the end of Hello And Good Morning James
good found in Hello And Good Morning James
 Good Morning
Hello And Good Evening James

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