How to find which perl module are installed in the system

There are two ways to view which perl modules are installed in the system.

1. perldoc perllocal Each time a module is installed on your system, it appends information about the module to a file called perllocal.pod
2. instmodsh command

daya@daya-laptop:~$ instmodsh

Available commands are:
l            – List all installed modules
m <module>   – Select a module
q            – Quit the program
cmd?

Processing string character by character:

A very useful function in Perl is split, which splits up a string and places it into an array. The function uses a regular expression and as usual works on the $_ variable unless otherwise specified. The split function is used like this:
$info = “Caine:Michael:Actor:14, Leafy Drive”; @personal = split(/:/, $info);
which has the same overall effect as
@personal = (“Caine”, “Michael”, “Actor”, “14, Leafy Drive”);
If we have the information stored in the $_ variable then we can just use this instead
@personal = split(/:/);
If the fields are divided by any number of colons then we can use the RE codes to get round this. The code
$_ = “Capes:Geoff::Shot putter:::Big Avenue”; @personal = split(/:+/);
is the same as
@personal = (“Capes”, “Geoff”,”Shot putter”, “Big Avenue”);
But this:
$_ = “Capes:Geoff::Shot putter:::Big Avenue”; @personal = split(/:/);
would be like
@personal = (“Capes”, “Geoff”, “”, “Shot putter”, “”, “”, “Big Avenue”);
A word can be split into characters, a sentence split into words and a paragraph split into sentences:
@chars = split(//, $word); @words = split(/ /, $sentence); @sentences = split(/\./, $paragraph);
In the first case the null string is matched between each character, and that is why the @chars array is an array of characters – ie an array of strings of length 1.
Ref:http://www.comp.leeds.ac.uk/Perl/split.html

Hash

Introduction
A hash is a two-dimensional array which contains keys and values, they’re sometimes called “associative arrays”, or “lookup tables”. Instead of looking up items in a hash by an array index, you can look up values by their keys.

Entire hashes are denoted by ’%’:
%days               # (key1, val1, key2, val2 …)
A Hash represents a set of key/value pairs.
my %fruit color = (“apple”, “red”, “banana”, “yellow”).
You can use whitespace and the “=>” operator to lay them out more nicely:
my %fruit_color = (
apple  => “red”,
banana => “yellow”,
);
To get at hash elements:
$fruit_color{“apple”};           # gives “red”
You can get at lists of keys and values with “keys()” and “values()”.

my @fruits = keys %fruit_colors;
my @colors = values %fruit_colors;
$days{‘Feb’}        # the ‘Feb’ value from hash %days

accessing the HASH Element
To access the hash element use the syntax like: ”’$hash{$some_key}”’ This is similar to what we used for array but here we used curly braces {} instead of square brackets. []

Input/Output

Standard Input
$line = <STDIN>;        # read the next line
chomp($line);           # and chomp it
chomp($line = <STDIN>); # same thing, more idiomatically

”’For array”’
@myarray = <stdin>
press Ctrl-D when done.

”’Diamond operator <>”’
<> operator is used if you want to make a perl program that can be used like the UNIX utilities such as cat, sed, awk, sort, grep lpr etc. The diamond operator is actually a special kind of line input operator. But instead of getting the input from the keyboard, it comes from the user’s choice of input.
while (defined($line = <>)) {
chomp($line);
print “$line\n”;
}
This program when executed with a filename as arguments will print the content of file line by line as of cat.
$line = <STDIN>;        # read the next line
chomp($line);           # and chomp it
chomp($line = <STDIN>); # same thing, more idiomatically

Since the line-input operator will return undef when you reach end-of-file, this is handy for dropping out of loops:

while (defined($line = <STDIN>)) {
print “I saw $line”;
}
shortcut
while (<STDIN>) {
print “I saw $_”;
}

Subroutines

Introduction
To avoid the dangerous practice of copying and pasting of code, large programs reuse chunks of code as subroutines.

”’Declaration”’
A subroutine is declared with the sub keyword. Here’s a simple subroutine definition:
sub hello {
$greeted++;          # global variable
print “hi there!\n”;
}

Invoking a Subroutine

The typical way of calling that subroutine is:
hello( );                 # call subroutine hello with no arguments/parameters
Another way of calling is putting Ampersand before the function name.
&hello

The term void context is just a fancy way of saying that the answer isn’t being stored in a variable or used in any other way.
Perl compiles your program before executing it, it doesn’t matter where subroutines are declared. Definitions don’t have to be in the same file as your main program. They can be pulled in from other files using the do, require, or use operators,

The last expression used in the sub routine is always the return type of a subroutine. So always be careful on it.

#!/usr/bin/perl -w
use strict;
my $var1 = 5;
my $var2 = 6;
my $sum  = &add;
my $mul = 7 * &add;
print "the vlaue of mul is : $mul \n";
print "the value of \$sum is: $sum\n";
sub add {
print "You called the add sub routine:\n";
$var1 + $var2;
}

Arguments

Perl has the subroutine arguments. To pass an argument list to the subroutine , simply place the list expression, in parentheses, after the subroutine invocation. like this

* $n = &max(10,30); # This sub call has two arguments.

Perl automatically stores the parameter list (another name for the argument list) in the special array variable named @_ for the duration of the subroutine. This means that the first subroutine parameter is stored in $_[0], the second one is stored in $_[1], and so on.

There is not any relation of these variable $_[0] $_[1] etc with $_.

eg.


#!/usr/bin/perl -w
use strict;
sub calculate {
my ($var1,$var2) = @_;
my $sum = $var1 + $var2;
print "the sum is: $sum\n";
}
&calculate(5,6);

Excess parameter is ignored in subroutine. And insufficient parameters are also ignored you simply get undef if you go beyond the array @_.For eg. &calculate(3,4,5,6,7). only first two parameters are considered and rest are ignored. The @_ variable is private to the subroutine; @_ is always the parameter list for the current subroutine invocation.A subroutine can pass arguments to another subroutine without fear of losing its own @_ variable – the nested subroutine invocation gets its own @_ in the same way. Even if the subroutine calls itself recursively, each invocation gets a new @_.

Return Values:
All perl subroutines have a return values. There is no distinction between those that return values and those that don’t. Whatever a calculation is last performed in the subroutine its the return value.
#!/usr/bin/perl -w
sub calculate {
my ($var1,$var2) = @_;
$var1 + $var2;
}
print “The sum is:”, &calculate(5,6), “\n”;
That code will product this output:
The sum is 11

#!/usr/bin/perl -w
sub calculate {
my ($var1,$var2) = @_;
$var1 + $var2;
print “This is daya:”;
}
print “The sum is:”, &calculate(5,6), “\n”;
This will product output as:
the sum is 1. In this example the last expression evaluated is not the addition; it’s the print statement. Its return value will normally 1, meaning “Printing was successful, but thats not the return value you actually wanted. ”’Last expression evaluated will be the return value.”’

Private Variable in Subroutines
By default all variables in the Perl are global variables; that is they are accessible from the every part of the program. You can create the private variable at any time called the lexical variable with”’ my”’ operator.
sub max {
my($m, $n);       # new, private variables for this block
($m, $n) = @_;    # give names to the parameters
if ($m > $n) { $m } else { $n }
}
These variables are private (or scoped) to the enclosing block; any other $m or $n is totally unaffected by these two.

”’Notes on Lexical Variable”’
Those lexical variable can be used in any block, not merely in the subroutine’s block. For example they can be used in the block of an if , while or foreach.
foreach (1..10) {
my ($square) = $_ * $_;
print “$_ squared is $square. \n”;
}
The variable $square is private to the enclosing block; in this case the block of foreach loop and is not accessible outside the block.Also note that my operator doesn’t change the context of an assignment.
my($num) =  @_; #List context, same as ($num) = @_;
my $num = @_; # Scalar context;, same as $num = @_;

It’s worth remembering that without the parentheses, my only declares a single lexical variable:
* my $fred, $barney;       # WRONG! Fails to declare $barney
* my($fred, $barney);      # declares both

Of course, you can use my to create new, private arrays as well:†
* my @phone_number;

”’The use strict Pragma”’

To tell Perl that you’re ready to be more restrictive, put the use strict pragma at the top of your program (or in any block or file where you want to enforce these rules):
* use strict;   # Enforce some good programming rules

”’The return Operator”’

The return operator immediately returns a value from a subroutine:
#!/usr/bin/perl -w
use strict;
my $sum;
sub calc{
print “Enter 1st no:”;
my $i = <STDIN>;
print “Enter 2nd no:”;
my $j = <STDIN>;
return ($i+$j);
}
$sum = &calc();
print “The sum is $sum\n”;

Recursion in Perl


* program to calculate Factorial
<pre>#!/usr/bin/perl -w
use strict;

sub fact{
my ($i) = @_; #used in list context
if ($i == 0) {
return(1);
}
else
{
return($i*fact($i-1));
}

}
my $var1;
print "Enter a no. to calculate fact:";
$var1 = <STDIN>;
chomp($var1);
print "The factorial of $var1 is:", &fact($var1),"\n";

Omitting the Ampersand & in the function call

If the compiler sees the subroutine definition before invocation, or if Perl can tell from the syntax that it’s a subroutine call, the subroutine can be called without an ampersand, just like a built-in function.The real rule to use is this one: until you know the names of all of Perl’s built-in functions, always use the ampersand on function calls.

Array

Introduction
If scalar is singular in perl then plural in perl are arrays and lists. A list is an ordered collection of scalars. An array is a variable that contains a list. In perl the two terms are used interchangeably, but to be accurate list is the data and array is the variable.
Declaration:

my @array = ( 2, 3, daya, maya, 6 )
when you use the use strict this syntax may be wrong, as having both number and name.
accessing the arrary variable:
$arrary[3]—> 3rd element
For acessing the whole array element, print @array
There are special array eg.
my @sorted = sort @arrary;
my @backwards = reverse @numbers;
etc

Array Indices
Last index of the Array can be retrieved by $#<array-name>
* eg.  $end = $#rocks;
The array size is dynamic, you don’t have to specify the size of the array. It automatically adjust depending upon your uses.There is no limit on its length as long as there is available memory.

-ve index:

* -1 index is used to access the last element of the array.

eg.


#!/usr/bin/perl
use strict;
my @var = (2,3,4,5,"daya","maya","test",6827);
print "@var\n";
print "The 3rd variable is: $var[3]\n";
my $lastindex = $#var;
print "The last element is:$var[$lastindex]\n";
print "the -2 index element: $var[-2]\n";

qw shortcut (Quoted words)
We frequently needs the list of words, the qw shortcut helps us to generate the list without typing a lot of extra quote marks.
* @listvar = (“daya”, “maya”, “test”, “ole”, “linux”);
* @listvar = qw(daya maya test ole linux); separate each of the element with the space bar.

range operator
(1..100) ===1 to 100.

List Assignment:
In much the same way as the scalar values are assigned to variable, list value may be also assigned to variables.
eg.
($name, $month, $salary) = qw(hari, feb, 5600);

Its very easy to swap in perl unlike in other language such as C which needs the temporary vaiables.

($var1, $var2) = ($var2, $var1);
it swaps the value of var1 and var2.
Note:

* $calar
* @rray
* To retrieve whole array , @array-name
* @array1 = @arrya2 —> copy one array to another.

Pop and Push Operators
* Helps to add and retrieve the array elements without using index.
* pop operator takes the last element of the array and returns it.
* push operator adds an element (or a list of elements) to the end of the array.

@array = 1..10
$var1 = pop(@array); #gets 10
$var2 = pop(@array); #get 9
push(@array,100); #push 100 to the end of the array.
push(@array, @others);

The shift and unshift Operators
It works in the same way as the push and pop but unlike push and pop does the operation at the end of the array or list it does at the beginning.
@array = 1..10
$var1 = shift@array; #gets 1
$var2 = shift@array; #gets 2
unshift(@array,5); # insert 5 at the beginning of the array

foreach control structure
The foreach loop steps through a list of values, executing one iteration for each value. foreach statement can be used in two ways.
1. using another variable to retrieve the element.
foreach $i (@array) {
print “$i”;
—-
}
2.Using Perl default variable $_ to retrieve element.
foreach (@array)
{
print “$_\n”;
—-
}
Special Array Operator
* sort operator
@sort = sort(@array); #sorts only the string.
* reverse operator
@rev = reverse(@array);
”’scalar and list context”’
The most important things to understand. The context refers to where an expression is found. As Perl is parsing your expressions,it always expects either a scalar value or a list value.* What Perl expects is called the context of the expression.
42 + something # The something must be a scalar
sort something # The something must be a list

@people = qw( fred barney betty );
@sorted = sort @people; # list context: barney, betty, fred
$number = 42 + @people; # scalar context: 42 + 3 gives 45

Even ordinary assignment (to a scalar or a list) causes different contexts:
@list = @people; # a list of three people
$n = @people;    # the number 3

Forcing Scalar Context
On occasion, you may need to force scalar context where Perl is expecting a list. In that
case, you can use the fake function scalar. It’s not a true function because it just tells
Perl to provide a scalar context:
@rocks = qw( talc quartz jade obsidian );
print “How many rocks do you have?\n”;
print “I have “, @rocks, ” rocks!\n”;        # WRONG, prints names of rocks
print “I have “, scalar @rocks, ” rocks!\n”; # Correct, gives a number
Oddly enough, there’s no corresponding function to force list context.

Using List-Producing Expressions in Scalar Context

$fred = something;            # scalar context
@pebbles = something;         # list context
($wilma, $betty) = something; # list context
”($dino) = something;          # still list context!”[[Link title]]
Don’t be fooled by the one-element list; that last one is a list context, not a scalar one.The parentheses are significant here, making the fourth of those different than the first.

”'<STDIN> in List Context”’

@lines = <STDIN>; # read standard input in list context
press CTRL-D at the last for the end of the input.

@lines = <STDIN>; # Read all the lines
chomp(@lines);    # discard all the newline characters
But the more common way to write that is with code similar to what we used earlier:
chomp(@lines = <STDIN>); # Read the lines, not the newlines

@days{‘a’,’c’}      # same as ($days{‘a’},$days{‘c’})

Conditions and Looping

Condition and Looping Construct
Perl has most of the usual looping and conditional construct expect the case and switch but it is also available in perl modules (CPAN).
if
if ( condition ) {

} elsif ( other condition ) {

} else {

}

unless
unless ( condition ) {

}

while
while
while ( condition ) {

}

for loop
for ($i = 0; $i <= $max; $i++) {

}

The C style for loop is rarely needed in Perl since Perl provides the more friendly list scanning foreach loop.

foreach
foreach (@array) {
print “This element is $_\n”;
}

Input in Perl
<STDIN> is used for input. eg.
print “/n Enter your 1st name:”
my $name =  <STDIN>;

Chomp Operator

This operator is used to remove the \n from the input and if the string ends in a newline character, chomp can get rid of the newline.

* $text = “a line of text\n”; # Or the same thing from <STDIN>
* chomp($text);               # Gets rid of the newline character

Basic program to show the demo:


#!/usr/bin/perl -w
# program to show the use of chomp operator. Take three text from user and print them as text1 | text2 | text3.
use strict;
my $var1;
print "Enter 1st text:";
$var1 = <STDIN>;
chomp ($var1);
print "Enter 2nd text:";
$var2 = <STDIN>;
chomp ($var2);
print "Enter 3rd text:";
$var3 = <STDIN>;
chomp ($var3);
print "The resulting text:\n";
print "$var1|$var2|$var3\n";

”’The undef value”’
What happen when you try to use the scalar value when its value is not initialized. It uses the undef. Its neither a string nor a number but a separate kind of the scalar value. As its value is equal to zero in case if used with number and empty string if used with string, so frequently used as string and number accumulator.

$string .= “more text\n”;  Acts as string accumulator.
$sum += 5;  Number Accumulator