Perl
Scalar variable: It is either a number or string. It has magnitude but no direction. It starts with $.
Integer Literals: They are straight forward as in 12, 15, 500, -300 etc. Don’t start the number with a 0, because Perl supports Octal numbers which starts with 0 (0377) and hex numbers start with 0x (-0xff).
Double quated string representations:
\n newline
\r return
\t tab
\b backspace
\a bell
\e escape
\cC any control character (In this example, it is CTRL + C)
\\ backslash
\" Double quote
\l lowercase next letter
\u uppercase next letter
\U Uppercase all following letters until \E
\L Lowercase all following letters until \E
\E Terminate \U, \E
Scalar Operator: An operator produces a new value (the result) from one or more other values (the operands). For example, + is an operator.
+, - , * , / (addition, substraction, multiplication and division operators)
/** is exponention operator. (2**3 is 2 to the third power, or 8)
% is modular operator ( 10 % 3 is the remainder when 10 is divided by 3 which is 1)
++ or - - (Auto incement or auto decrement)
x is string repetition operator. “fred” x 3 gives fredfredfred and 4 x 4 gives 4444 as output.
&& (logical and), || (Logical OR)
‘.’ Concatenate operator. “X” . (4 * 5) # same as “X” . 20 or X20.
= += -= *=, etc… Assignment and binary assignment ( $a=$a+5 and $a +=5 are same)
Number and string comparision:
The eg (equal), ne, lt, gt, le, ge operators compares 2 strings.
($name eq "jeeva")
== (equal), != (not equal), <, >, <=, >= operators compares 2 numeric values.
($number == 10)
Binary Assignment Operator:
Nearly all binary operators that compute a value have a corresponding binary assignment form with an appended equals sign. For example, the following two lines are equivalent:
$fred = $fred + 5; # without the binary assignment operator
$fred += 5; # with the binary assignment operator
These are also equivalent:
$barney = $barney * 3;
$barney *= 3;
$str = $str . " "; # append a space to $str
$str .= " "; # same thing with assignment operator
Autoincrement and Autodecrement:
$a =+ 1; # with assignment operator
++$a ; # with prefix autoincrement
$d = 17;
$e = ++$d; # $e and $d are both 18 now.
Here, the ++ operator is being used as a prefix operator; that is, the operator appears to the left of its operand. The autoincrement may also be used in a suffix form (to the right of its operand). In this case, the result of the expression is the old value of the variable before the variable is incremented. For example:
$c = 17;
$d = $c++; # $d is 17, but $c is now 18.
To get Standard input and remember as variable, <STDIN> construct is used.
$name = <STDIN>;
To remove the trailing new line (\n) character, use "chomp" funtion.
chomp ($name); or chomp ($a = <STDIN>);
To remove the last character, use chop funtion.
chop ($name);
Array Variable:
An array variable starts with @. An array is a variable that holds a list. Each element of the array is a separate scalar variable. A list literal consists of comma separated values enclosed in parentheses.
@words = ("Jeeva","Nandam","Kailasam","Nadar"); or qw (Jeeva Nandam Kailasam Nadar)
List constructor operator: Indicated by two scalar values separated by two consecutive periodes. This operator creates a list of valuess starting at the left scalar value up through the right scalar value, incrementing by one esch time. For example,
(1 .. 5) # Same as (1, 2, 3, 4, 5)
(1.2 .. 3.2) # Same as (1.2, 2.2, 3.2)
($a .. $b) # Range determined by current values of $a and $b
If a list literal contains only variable references (not expressions), the list literal can also be treated as a variable. In other words, such a list can be used on the left side of an assignment. Each scalar variable in the list literal takes on the corresponding value fromn the list on the right side of the assignment. For example:
($a,$b,$c) = (1,2,3); # give 1 to $a, 2 to $b, 3 to $c
($a,$b) = ($b,$a); # swap $a and $b
($d,@fred) = ($a,$b,$c); #give $a to $d and ($b,$c) to @fred
Array element access: Array element are numbered using sequential integers, beginning at zero and incresing by one for each element.
@fred = (7,8,9);
$b = $fred[0] ; # give 7 to $b
$fred[2]++; # incremet the third element of @fred
Accessing a list of elements from the same array is called a slice. This slice uses an @ prefix rather than $.
@fred[0,1]; # same as ($fred[0], $fred[1])
@fred[1,2] = (9,10); # change the last 2 values to 9 and 10.
Slices also work on literal lists, or any funtion that returns a list value.
@who =(qw(fred baney betty wilma)) [2,3]; # same as @who = wq(betty wilma);
Assigning a value to beyond the end of the current array automatically extends the array (giving value of undef to all intermediate values). For example:
@fred = (1,2,3);
$fred[3] = “hi”; # @fred is now (1,2,3,”hi”)
$fred[6] = “ho”; # @fred is now (1,2,3,”hi”,undef,undef,”ho”)
print $#fred; # prints the index value of the last element. Here it is 6.
The push and pop funtions: Push and Pop funtions do things to the right side or a list.
push (@mylist,$newvalue); # Like @mylist = (@mylist, $newvalue);
$oldvalue = pop (@mylist); # removes the last element of @mylist.
The shift and unshift function: Unlike push and pop, shift and unshift functions performs actions on the left side of the list.
@fred = (5,6,7);
unshift (@fred,2,3,4); #fred is now (2,3,4,5,6,7)
$x = shift (@fred); # $x is now 2 and @fred is now (3,4,5,6,7)
The reverse function: The reverse operator takes a list of values (which may come from an array) and returns the list in the opposite order.
@fred = 6..10;
@barney = reverse(@fred); # gets 10, 9, 8, 7, 6
@wilma = reverse 6..10; # gets the same thing, without the other array
The sort Function: The sort operator takes a list of values (which may come from an array) and sorts them in the internal character ordering
@rocks = qw/ bedrock slate rubble granite /;
@sorted = sort(@rocks); # gets bedrock, granite, rubble, slate
H-ash Variable:
A hash variable starts with %. Each element of hash is a separate scalar
vaiable. But it is referenced by a key value.
%words = qw ( fred camel barney funny betty aplaca );
In the above example, camel is referenced by a key fred and funny by the
key barney. $words{fred} gives camel and $words{barney} gives funny.
Regular Expressions:
Regular expressions are deliminated by slashes.
To look for any string that begin with 'randal'
if ($name =~ /^randal/)
To ignore the case, append 'i' after the closing slash
if ($name =~ /^randal/i)
Word boundary special marker \b is used to mention there is no letter, digits or any special charabtes after this marker.
if ($name =~ /^Randal\b/i/)
In the above example, the condition is true if the $name starts with Randal and there is no letters or digits after the letter 'l' and also it is not case sensitive.
\W look for non-word character (some thing besides letters, digit, or underscore)
To find out the first non word character and to zap everything from there to the end of the string from $name:
$name =~ s/\W.*//;
\W ---> looks for non word character
.* ---> any character from there to the end of the line
s ---> substitute operator. It is followd by slash deliminated regular expression and string (in the above example, it is empty string which replaces non word charaters with nothing)
To put the contents of $name in to lowercase letters ‘tr’ operator is used:
$name =~ tr/A-Z/a-z/;
Here are some special RE characters and their meaning
. # Any single character except a newline ^ # The beginning of the line or string $ # The end of the line or string * # Zero or more of the last character + # One or more of the last character ? # Zero or one of the last character \w # Any alphanumeric (word) character. Same as [a-zA-Z0-9_] \W # Any non-word character. Same as [^a-zA-Z0-9_] \d # Any digit. The same as [0-9] \D # Any non-digit. The same as [^0-9] \s # Any whitespace character: Space, tab, newline, etc \S # Any non-whitespace character \b # A word boundary, outside [] only \B # No word boundary
CONTROL Structures
Statement Blocks: It is a sequence of statements, enclosed in catching curly braces. It looks like
{
first_statement;
second_statement;
……
last statement;
}
if /unless Statement
if (some expression) {
true_satemets;
} else {
false_statemenrs;
}
We can replace the if conditon with ‘unless’ condition. ‘unless’ execute the statements, if the conditions is false. ‘unless’ can also have an else, just like an if.
If you have more than two choices, add an elsif branch to the if statement.
while / until Loop
while ( some_expression) {
statement_1;
statement_2;
}
The do {} while/until Statement: The while/until statement tests its condition at the top of every loop, before the loop is entered. If the condition was already false to begin with, the loop won't be executed at all.
But sometimes you don't want to test the condition at the top of the loop. Instead, you want to test it at the bottom. To fill this need, Perl provides the do {} while statement, which is just like the regular while statement except that it doesn't test the expression until after executing the loop once.
do {
statement_1;
statement_2;
} while some_expression;
The for Statement
for ( initial_exp; test_exp; re-init_exp ) {
statemenr_1;
statement_2;
}
The foreach Statement: This statement takes a list of values and assigns them one at a time to a scalar variable., executing block of code with each successive assignment. It looks like this:
foreach $i (@some_list) {
Statement_1;
Statement_2;
}
Example of foreach:
@a=(1,2,3,4,5);
foreach $b (reverse @a) {
print $b;
}
The last command is like the break statement in C (as used in loops); it immediately exits the loop in question
Perl's Favorite Default Variable: $_
If you omit the control variable from the beginning of the foreach loop, Perl uses its favorite default variable, $_.
foreach (1..10) { # Uses $_ by default
print "I can count to $_!\n";
}
Although this isn't Perl's only default by a long shot, it's Perl's most common default. Perl will automatically use $_ when you don't tell it to use some other variable or value, thereby saving the programmer from the heavy labor of having to think up and type a new variable name. One of those cases is print, which will print $_ if given no other argument:
$_ = "Yabba dabba doo\n"; print; # prints $_ by default
File Handles and File tests
$! variable, which contains the error string describing the most recent operating system error. It's used like this:
open(LOG, ">>logfile") || die "cannot append: $!";
$filename = <STDIN>;
chomp $filename; # toss pesky newline
if (-r $filename && -w $filename) {
# file exists, and I can read and write it
...
}
File Tests and Their Meanings
Test Meaning
-r File or directory is readable
-w File or directory is writable
-x File or directory is executable
-o File or directory is owned by user
-R File or directory is readable by real user, not effective user
(differs from -r for setuid programs)
-W File or directory is writable by real user, not effective user
(differs from -w for setuid programs)
-X File or directory is executable by real user, not effective user
(differs from -x for setuid programs)
-O File or directory is owned by real user, not effective user
(differs from -o for setuid programs)
-e File or directory exists
-z File exists and has zero size (directories are never empty)
-s File or directory exists and has nonzero size
(the value is the size in bytes)
-f Entry is a plain file
-d Entry is a directory
-l Entry is a symlink
-S Entry is a socket
-p Entry is a named pipe (a "fifo")
-b Entry is a block-special file (like a mountable disk)
-c Entry is a character-special file (like an I/O device)
-u File or directory is setuid
-g File or directory is setgid
-k File or directory has the sticky bit set
-t isatty() on the filehandle is true
-T File is "text"
-B File is "binary"
-M Modification age in days
-A Access age in days
-C Inode-modification age in days
Functions
timelocal and localtime are two different functions.
To find out today’s date:
($DAY, $MONTH, $YEAR) = (localtime)[3,4,5]; ( the out put format : month is 0 for Jan and 11 for Dec and year is actual year – 1900)
Or, use Time::localtime, which overrides localtime to return a Time::tm object:
use Time::localtime; $tm = localtime; ($DAY, $MONTH, $YEAR) = ($tm->mday, $tm->mon, $tm->year);
Converting DMYHMS (Date, Month, Year, Hour, Min, Sec) to Epoch Seconds
Use the timelocal or timegm functions in the standard Time::Local module. Replace 'timelocal' with 'timegm' if your input date is GMT/UTC
use Time::Local; $TIME = timelocal($sec, $min, $hours, $mday, $mon, $year);
Here's an example that shows how to find Epoch seconds for a time in the current day. It gets the day, month, and year values from localtime:
use Time::Local; $time = timelocal($seconds, $minutes, $hours, (localtime)[3,4,5]);
time function gives today’s date in epoch seconds
localtime(epoch seconds) converts epoch seconds to readable format.
Converting epoch seconds to DMYHMS:
($seconds, $minutes, $hours, $day_of_month, $month, $year,
$wday, $yday, $isdst) = localtime($time);
or
use Time::localtime;
$tm = localtime($time);
printf("Dateline: %02d:%02d:%02d-%04d/%02d/%02d\n",
$tm->hour, $tm->min, $tm->sec, $tm->year+1900,
$tm->mon+1, $tm->mday);
# perl -le 'print scalar localtime 12545 * 24 * 60 * 60 '
Thu May 6 17:00:00 2004
cat time.pl
#!/usr/bin/perl
$a = time ;
print "$a \n";
print scalar localtime (time) ;
# ./time.pl
1087418422
Wed Jun 16 13:40:22 2004
PERL ADMIN STUFFS:
To run your program with warnings turned on, use the -w option on the command line:
$ perl -w my_program
To find out the Installed perl modules, use the following script.
- !/usr/bin/perl
use ExtUtils::Installed;
my $instmod = ExtUtils::Installed->new();
foreach my $module ($instmod->modules()) {
my $version = $instmod->version($module) || "???";
print "$module -- $version\n";
}
Each time a module is installed on your system, it appends information to a file called perllocal.pod which can be found in /usr/local/lib/perl5/version number/architecture/ or something akin to that. We can find out the installed modules by running the following command.
# cat perllocal.pod | grep Module
To install new Perl modules:
The CPAN module is designed to automate the make and install of perl modules and extensions. It includes some searching capabilities and knows how to use Net::FTP or LWP (or lynx or an external ftp client) to fetch the raw data from the net. Modules are fetched from one or more of the mirrored CPAN (Comprehensive Perl Archive Network) sites and unpacked in a dedicated directory.
Installing a new module can be as simple as typing perl -MCPAN -e 'install Chocolate::Belgian'.
To go to interactive mode,
perl -MCPAN -e shell
Once you are on the command line, type 'h' and the rest should be self-explanatory.
To automatically install the perl modules
# perl -MCPAN -e 'install DBD::mysql'