Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Language
Introduction to PERL
Chapter 1
Introduction to Perl
Practical Extraction and Report Language
Developed by Larry Wall
Optimized for:
Scanning arbitrary text files
extracting information from those text files
printing Reports
Available in almost all OS platforms: UNIX, DOS,
Introduction to Perl
Perl combines some of the best but simple features of
c
sh
awk
sed
Syntax corresponds quite closely to C expressions
Free-format language
Typically Perl program is indented much like C
Basic Concepts
Perl is both a Compiler and Interpreter
It is compiler because the program is completely read and parsed
Basic Concepts
Shell script - a sequence of shell commands
$ echo date > somescript
$ echo who >> somescript
$ cat somescript
date
who
$ chmod +x somescript
$ somescript
[output of date and who commands will be displayed]
Basic Concepts
Perl program is a bunch of perl statements and definitions thrown
into a file
The first statement is
#! /usr/bin/perl
Perl comments are like shell comments:
# Anything from here till end of line
# NO C like multiline comments
First Example
#! /usr/bin/perl -w
print (Hello, World!\n);
Scalar Data
Chapter 2
Scalar Data
Scalar Variable
Numbers
Numbers
Ex.
1.25
# decimal number
7.25e12
# 7.25 time 10 to power of 12
-6.5e12
# 6.5 times 10 to the 12th power
-6.65
# negative decimal number
12
12 # simple integer
Octal & Hex
Ex.
0377 # 377 octal, same as 255 decimal
0xff # FF hex, same as decimal 255
Strings
Strings
In a single quote string
character within the quote is legal (including \n, \t etc.) except
when a quote is to be used, precede it with \ and for a
backslash precede it with another backslash.
Ex.
hello
# simple string of five chars.
don\t
# quote of dont is preceded with \
silly\\boy
# silly\boy, the backslash is preceded with \
hello\n
# a string as is hello backslash and n
hello
# word hello a newline and word there
there
Strings
In a double quoted string the backslash specifies the control
characters or any character through octal and hex
representations.
Ex.
hello world\n #string hello world and newline
new \127
#new, space and the del char. In octal.
coke\tsprite
#coke, a tab and sprite
cant
#cant word
Operators
Number operators :
Perl provides the normal addition, subtraction,
multiplication , division and the exponentiation
operators including the modulus.
Ex.
2+3
# 2 plus 3, or 5
5.1 2.4
3 * 12
14 /2
10.2 / 0.3
2 ** 3
10 % 3
10.5 % 3.2
Operators
Logical comparison operator :
These are operators such as <, <=, = =, >=, !=, > which compare
two values numerically and return a true or false
String Operators :
String values can be concatenated with the . operator (period).
Ex.
hello . world
#same as helloworld
hello world . \n
# same as hello world\n
Operators
Numeric and String comparison operators :
Numeric
Equal
Not Equal
Less Than
Greater than
Less than or equal
Greater than or equal
==
!=
<
>
<=
>=
String
eq
ne
lt
gt
le
ge
# assigns 17 to variable $a
# give $b the value of $a plus 3 , (20)
# give $b the value of $b * 2 (40)
Defined OR
Use ? : operator to evaluate an expression and return a value based on
whether the expression is true or false.
$var1 = part1;
$var2 = part2;
$var3 = defined($var1) ? $var1 : $var2;
# defined function evaluates whether var1 is defined or not
# returns var1 if var1 is defined else returns var2
This can also be written using a simpler operator // (available from
V5.10)
$var3 = $var1 // $var2;
Ex.
print (hello world\n);
print hello world\n;
Control Structures
Control Structures
A statement block is a sequence of statements,
enclosed in matching curly braces.
{
statement;
statement;
statement;
}
Ex.
0
1-1
1
1
undef
# converts to 0, so false
# computes to 0, the converts to 0, so false
# converts to 1 , so true
# Blank string, converts to false
# not or 0, therefore true
# evaluates to , therefore false
Ex.
print how old are you ?;
$age = <STDIN>;
chomp($a);
if ($age < 18) {
print Kid, you are not old
enough to vote\n;
} else {
print Old enough. Go
vote !\n;
$voter++;
}
Note that both in while and until form, the body is skipped entirely, if the first
time itself the expression is false.
Looping - Example
#! /usr/bin/perl -w
# Guessing a secret word
$secretword = Guess;
print What is your name? ;
chomp($name = <STDIN>);
print Hello $name! \n;
print what is the secret word? ;
chomp($guess = <STDIN>);
# This is a while loop
while ($guess ne $secretword) {
print Wrong, Try again. what is the secret word?;
chomp($guess = <STDIN>);
}
List Data
A literal list consists of comma separated values enclosed in
parentheses.
Ex.
(1,2,3)
#list of three values 1,2 & 3
(dog,10.5)
# list of two values, dog and 10.5
The elements of a list can also be expressions. The expression is
reevaluated each time it is referred.
($a, 17);
($a+$c, $d+$e)
Ex.
( 1 .. 5 )
# value as 1,2,3,4,5
(1.2 .. 5.2)
# values as 1.2, 2.2, 3.2, 4.2, 5.2
(2 .. 4, 10, 12) # values as 2,3,4,10,12
($a .. $b) # range determined by current value of $a and $b
Arrays in Perl
@words = (Gold, Silver, Pearl); or as
@words = qw(Gold Silver Pearl);
Array Variables
Array variable names are similar to scalar variable names, except
that the first char. $ is replaced by @.
Ex.
@myarray
Initializing Arrays
Assigning a literal list to Arrays
@a = ( dog, cat, mouse, goat );
you can also write as
@a = qw(dog cat mouse goat ) ;
The quote word function uses the space character as the
delimiter.
You can also write as;
@a = qw(
dog
cat
mouse
goat );
#initialize array
# $cnt will get 3, the current length
of array
Ex.
push(@myarr, $newval);
# same as @myarr =
(@myarr, $newval);
$oldval = pop( @myarr );
# remove the last element
from myarr
<STDIN> as an Array
Ex.
@a = <STDIN>; #reads standard input in a line
context
# $x contains This is
dollys place
# returns this is dolly
# this returns correct because
of braces
# also correct
Ex.
@arr1 = (sue, sam, harry);
$all = The kids @arr1 are here;
foreach $i ( @some_list )
statement_1;
statement_2;
}
Ex.
@a = (1,2,3,4,5);
foreach ( reverse @a ) {
print ;
}
Switch Operation
use feature qw (switch say);
my @guessed_num;
my $num = int (rand 100)+1;
while (my $guess = <STDIN> ) {
chomp $guess;
given($guess){
when(/\D/){say "Please enter an integer"}
when(@guessed_num){say "tried already"}
when($num){say "perfect"; last}
when(10){say "Tired?"; last}
push (@guessed_num, $_);
}
}
Switch Operation
use feature switch;
Hashes
Hash Variable
Hash variable names are indicated by a percent sign
(%) followed by the same characters as in defining a
scalar (letter, digits and underscore).
Thus $myvar and @myvar and %myvar are
unrelated to one other.
To refer to an element of a hash %myvar, use
$myvar{$key}
Hash Variable
To create a new element of a hash use the assignment as;
$myvar{aaa} = bbb;
$myvar{234.5} = 456.8;
# prints bbb
# makes the value 459.8
@my_list = %myvar;
Example
%myhash = ();
#force empty %myhash
$myhash{one} = asterix;
$myhash{two} = obelix;
@lastname = values(%myhash);
#grab the values
The last statement will put (asterix,obelix) or (obelix, asterix)
in @lastname.
Ex.
while (( $first, $last ) = each (%lastname)) {
print The last name of $first is $last\n;
}
Note: Assigning new value to the hash resets the each function to
the beginning. Adding or deleting elements of hash is likely to
confuse each.
Ex.
%myhash = (aaa, bbb, 123, 455.5 ); #assign two values
to hash
delete $myhash{aaa};
Hash Slices
To find if the mail message is from merlyn, we look for From line
and then see if the id is merlyn.
Ex.
while ( something )
{
:
if ( somecondition)
somepart;
:
next;
}
otherpart;
:
# next comes here
}
If somecondition is true,
then somepart is executed,
and otherpart is skipped.
Like last, even in next the
if statement does not count
as a looping block.
Ex.
while ( something )
{
# redo comes here
:
if ( somecondition)
somepart;
:
redo;
}
otherpart;
:
}
Labeled Blocks
To jump out of block, or exit from two nested blocks
at once, you can use last, next and redo on an
enclosing block by giving it a name with a label.
The label follows the same naming conventions and
is in a separate namespace.
It is better to use labels as uppercase consisting of
letter and digits.
Labeled Blocks
Ex. 1
SOMELABEL:
while ( condition ) {
Statement;
:
:
if ( othercondition ) {
last SOMELABEL;
}
}
The last statement with label as parameter, tells perl to exit
the block named SOMELABEL, rather than just innermost
block.
Labeled Blocks
Ex. In nested loops:
OUTER: for ($i = 1; $i <= 10 ; $i++ ) {
INNER: for ($j; $j <= 10; $j++ ) {
if ($i * $j ) == 63 {
Print $i times $j is 63 ! \n;
Last OUTER;
}
if ( $j >= $i ) {
next OUTER;
}
}
The 2nd if checks if inner loop number is greater than the outer loop numbers.
If so, it loops to the next iteration of the outer loop with next OUTER. Thus, only
9 * 7 = 63, is the result.
Expression Modifiers
Perl allows usage of an if modifier onto an expression that is
a standalone statement.
Some-expression if control_expression;
Here the control_expression is evaluated first for truth value,
and if true, some-expression is evaluated next. This is similar
to
If ( control_expression ) {
Some_expression;
}
Expression Modifiers
Ex.
LINE: while <STDIN> {
Last LINE if /^From: /;
}
Other variants include;
Exp2 unless exp1;
Exp2 while exp1;
Exp2 until exp1;
Expression Modifiers
Ex.
To find first power of two greater than a given number;
Chomp($n = <STDIN>);
$i = 1;
$i *= 2 until $i > $n;
print The value of power of two Greater than $n is $i \n;
Note:
This form does not nest.
Exp2 consists of single statement.
Basic IO
Ex.
Suppose we have a program name kitty.pl as;
#!/usr/bin/perl
while (<>) {
print $_;
}
and you invoke perl kitty.pl file1 file2
Output to STDOUT
Ex.
Printf %15s %5d %10.2f\n, $s, $n, $r;
M operator returns the age in days since a file or filehandle has last
been modified.
If in our example we wanted to check whether the file has been
modified in the last 7 days, we need to check whether the M
operator return a value >= 7 as
sub init_words {
open (WORDLIST, wordlist) | | die cant open wordlist: $!;
if (-M WORDLIST >= 7.0 ) {
print The file wordlist is not modified for Seven days at least;
}
close ( WORDLIST ) | | die cant close file: $!;
}
Functions
Subroutines in Perl
Subroutines can be created and called from other places
in a perl code.
A subroutine has:
Name
Parameters
Return Value
Functions
A user function is called a subroutine or sub.
It is defined in a perl program as;
sub subname {
Statement_1;
Statement_2;
Statement_3;
}
The subname is the name of the subroutine. The name does
not have @ or $ or % so can have the same name as a
variable or array or hash.
Functions
Ex.
Sub say_hello{
Print hello, world \n;
}
Return Values
Ex.
$a = 3; $b = 4;
$c = sum_of_a_and_b();
$d = 3 * sum_of_a_and_b();
Sub sum_of_a_and_b {
return $a + $b;
}
Function Arguments
Ex.
Sub say_hello_to {
Print hello, $_[0]!\n;
}
$_[0] is the 1st element of the @_ array. This is not the same
as $_.
Function Arguments
Less or more parameters in perl are ignored.
The @_ is private to the subroutine.
If there is global value for @_, it is saved away before the
subroutine is invoked and restored to previous value upon
return to previous value.
Therefore a subroutine can pass arguments to other
subroutines without losing its own @_ values.
Ex.
$a = add(4,5,6);
print add(1,2,3,4,5);
print add(1..5);
Sub add {
$sum = 0;
foreach $_ ( @_ ) {
$sum += $_;
}
return $sum;
}
Subroutines - Example
The example below is for finding the validity of the
Subroutines - Example
sub pass_word {
my($key, $passwd) = @_; # name the parameters
$key =~ s/\W.*//; # get rid of everything after first word
$key =~ tr/A-Z/a-z/; # convert to lower case
if ($key eq larry) {
return 1;
} # return true
elsif ( ($words{$key} || guest) eq $passwd ) {
return 1 ;
}
else {
return 0;
} # return false
}
Subroutines - Example
#!/usr/bin/perl
%words = qw (
asterix
clever
oblix
fat
dogmatix
dog );
print What is your Name ?;
chomp($name = <STDIN>);
if ($name =~ /^larry\b/i ) {
print Hello, Larry!\n;
} else {
print Hello, $name!\n;
$passwd = $words{$name};
Subroutines - Example
if ($passwd eq ) { # not found in hash
$passwd = guest;
}
print What is the Password ?\n;
chomp($pwd = <STDIN>);
while ( ! pass_word($name, $pwd)) {
print wrong password, try again!\n;
print What is the Password ?\n;
chomp($pwd = <STDIN>);
} # end of while
} # end of not Larry
Ex.
Sub add {
my ($sum);
$sum = 0;
foreach $_ ( @_ ) {
$sum += $_;
}
return $sum;
}
foreach $_ ( @values ) {
if ($_ > $n) {
push( @result, $_ );
}
}
return @result;
# return final list
}
This prints;
Current value is original
Current value is temporary
Current value is original
Local can be used for the perls built-ins also, like $_, @_,
@ARGV.
AUTOLOAD
The AUTOLOAD mechanism, built into the definition of Perl packages,
AUTOLOAD
use strict;
use warnings;
use vars '$AUTOLOAD';
# global variable declaration
print "I started the program\n";
report_magical_function("one", "two");
print "I got to the end of the program\n";
sub AUTOLOAD {
print "AUTOLOAD is set to $AUTOLOAD\n";
print "with arguments ", "@_\n";
}
BEGIN
BEGIN {
print Executed at the start of the process and before any other
code.\n";
}
print Programs execution sequence...\n";
die Terminate the program...\n";
END {
print " Executed at the end of the process even if there is an
error in normal program sequence.\n";
}
Typeglob
Variable of same name but different context can coexist at any point in
time. They all are stored together and can be accessed using one
reference.
Use the variable type (context) to access them individually.
$test = "This is a new line";
@test = (124, 464, "Whats the matter?");
%test = (987, "First", 394, "Second");
$a1 = *test{SCALAR};
$a2 = *test{ARRAY};
$a3 = *test{HASH};
Regular Expressions
Regular Expressions
A regular expression ( also called template) is a pattern to be
matched against a string.
The pattern can be used for replacement of a new pattern
etc.
Regular expression is used by programs such as grep, awk,
sed, vi etc.
Perl is a semantic superset of these.
Ex.
While (<>) {
If (/abc/) {
Print $_;
}
}
Ex.
In perl;
While (<>) {
If (/ab*c/) {
Print $_;
}
}
The above can handle strings beginning with Larry, but not larry.
translate operator tr as
$name =~ tr/A-Z/a-z/;
Therefore, $name =~ s/\W.*//; # gets rid of all chars
s/ab*c/def/;
Patterns
A regular expression is a pattern.
Some patterns are for a single char.
Patterns are also for multiple chars.
Negated character class (^), is the same as a character class, but the caret(^) is
immediately after the opening bracket.
Example
[^0-9]
# any non digit char.
[^aeiouAEIOU]
# anything which is not a vowel
[^\^]
$ any single char which is not a caret (^).
Equivalent
Class
Negated
Construct
Equivalent
Negated Class
\d ( a digit )
[0-9]
\D (digits not! )
[^0-9]
\w ( a word)
\S (space, not! )
[^a-zA-Z0-9_]
[^ \r \t \n ]
The \d matches one digit. The \w one word and the \s a space char. The
negated chars. are \D, \W and \S.
These abbreviated classes can be used as part of other char. classes as well;
like
[\da-fA-F]
Pattern Types
Grouping Patterns
In groups you can say one or more of these or up to five of those etc.
Sequence
A multipler can be asterisk (*) indicating zero or more of the previous char. or
char. class.
A plus (+), one or more of immediately previous char., and quistion mark (?)
meaning zero or one of the immidiately previous character.
Pattern Types
Ex. 1
/fo+ba?r/
which is an f followed by one or more of os followed by b,
followed by an optional a followed by r.
Ex. 2
$_ = home xxxxxxx home;
s/x+/sweet/;
Replaces all xs with sweet and results in home sweet
home.
General Multipliers
To say five to Ten xs, we use general multipliers as;
/x{5,10}/.
The general multiplier has curly braces with one or two numbers inside. In this case
letter x must have 5 to 10 repetitions.
Now, seems you can get rid off *, + and ? as they are equivalent to {0, }, {1, } and {0,1},
however it is easier to type the equivalent single punctuation character.
Parentheses as memory
Example
([a]) matches an a, and
lowercase letter.
Parentheses as memory
To recall a memorized string, you must include a backslash
followed by an integer.
Ex.
/Asterix(.)obelix\1/;
The above example matches a string consisting of Asterix,
followed by any char other than newline char. (dot is in
parentheses for any char and brackets for memorizing ),
followed by obelix and again any single char. ( i.e. repetition of
memorized 1st pattern (.) indicated by \1 ).
Parentheses as memory
In the previous example, the \1 indicated the first parenthesized part of a regular
expression.
If there are more than one, the second part is referred as \2, the third as \3 and so
on. Counting is from left to right
Example
/a(.)b(.)c\2d\1/;
Here the 1st group (.) after a is #1 and (.) after b is #2, and c is followed by repetition of
#2 and d that of #1.
Alternation
Anchoring Patterns
Matching a string to a pattern generally takes from left to right, at the first possible
opportunity.
Anchors allow you to ensure pattern line up with particular parts of the string.
Anchoring Patterns
Example
/\bfred\B/;
Anchoring Patterns
Ex.
Precedence of Anchors
Examples of regular expressions and effect of parenthesis
Abc*
(abc)*
^x|y
^(x|y)
a|bc|d
(a|b) (c|d)
(song|blue)bird
# true
# also true (matches the double l)
# true, so yes
# some stuff
Ignoring Case
In the previous case we used [Yy] to match either a lower or upper case y.
To match a string with ignore case, you can use /somestring/i, which will match with
either case.
Print any last request ? ;
If (<STDIN> =~ /^y/i) {
:
}
Variable Interpolation
A regular expression can be variable interpolated before it is considered for special
chars.
Thus, you can construct a regular expression from computed strings rather than just
literals.
Example
$what = bird;
$sentence = Every bird has wings;
if ($sentence =~ /\b$what\b/) { # use of variable reference for
/\bbird\b/
print the sentence contains the word $what!\n;
}
another way;
$_ = this is a test;
($first, $second) = / (\w+) \W+ (\w+)/; # match first two words
# $first is now this and $second is now is
Other predefined read-only variables are $&, which is the part that matched regular
expression
and $`, which is the part of string before the part that matched
and $ which is the part of string after the part that matched.
Example
$_ = "this is a sample string";
/sa.*le/;
# matches "sample" within the string
# $` is now "this is a "
# $& is now "sample"
# $ is now " string"
Substitution
Apart from the simple substitution operator s/old-string/new-string/, there are several
variations also.
To substitute multiple occurrences, use g at the end;
Example
$_ = "foot fool buffoon";
s/foo/bar/g;
Substitution
To have variable interpolation in the replacement string ;
Ex.
$_ = "Hello world";
$new = "Goodbye";
s/Hello/$new/;
Pattern chars can be used in regular expression to allow pattern matching, rather than
just fixed chars.
$_ = "this is a test";
s/(\w+)/<$1>/g; # $_ is now "<this> <is> <a> <test>"
Finding a string
To locate a string (substring) within a string, you can use index function.
The index locates the first occurrence of the substring within the string.
Ex.
$x = index($string, $substring);
Finding a string
Ex.
$where = index(hello, e);
# $where gets 1
$name = barney;
$where = index (fred barney,$name);
# $where gets 5
@rockers = (fred, barney);
$where = index(join( ,@rockers),$name); #$where gets 5
$which = index(a very long long string, lame); # $which gets 1
To get the 2nd occurrence instead of the 1st, use the third parameter of index, which
is the start posn.
$x = index($string, $substring,$startpos);
Ex.
$which = index(a very long long string, long, 9);
#$which gets
12
Finding a string
Example
$where = rindex(hello world, l);
$where = rindex(hello world, o);
$where = rindex(hello world, o,6);
The substr function is used to pull out a part of a string from a string.
The substr function takes three arguments.
A string value, a start position (1st pos is 0 or pos-1 is the start pos ) and a length
(which can be longer than remaining chars in string).
Ex.
$s = substr($string, $start, $length);
$hello = hello;
$s = substr($hello, 3,2);
$s = substr($hello, 3,200);
# $s gets lo
# $s gets lo
# $s gets ll
# $s gets o
If the start is big ve number (greater than length of string), the start posn. defaults
to the beginning i.e. 0.
Omitting the legth is same as including a large length, or up to the end.
To replace a substr, you can have the substr in the left side of an expression as;
$hw = hello world;
substr($hw, 0,5) = howdy;
Here the chars returned by substr function are removed and the assigned chars ( on
right ) are substitued in place.
The length of string being assigned (right side) is immaterial as in;
$hw = hello world;
substr($hw, 0,5) = hi;
# replaces hello with hi
Advanced Sorting
Advanced Sorting
Here, the comparison is your comparison, only the return values are fixed.
It can be any logic which you choose and this makes the perl sort so flexible.
Advanced Sorting
In ordinary sort ;
@somelist = (1,2,4,8,16,32,64,128,256);
@outlist = sort @somelist; # @outlist is now
(1,128,16,2,256,32,4,68,8)
Using sort with our subroutine;
@outlist = sort by_number @somelist;
# outlist is now (1,2,4,8,16,32,64,128,256)
Advanced Sorting
Since, numeric comparison is quite common in sort, perl has a special operator to do
this called the spaceship operator (<=>).
Using this the earlier by_number subroutine can be written as;
Sub by_number {
$a <=> $b;
}
In fact instead of writing as ;
@outlist = sort by_number @somelist;
You can now write as ;
@outlist = sort { $a <=> $b} @somelist;
Advanced Sorting
Just as the spaceship operator is for numeric comparison, perl has a string
comparison char cmp.
To sort a hash on names which contains ids as keys and names as values.
Directory Access
Changing Directory
Similar to cd command in MS-Dos and Unix to move around the directories, perl
used chdir function.
chdir returns true when you have successfully changed to the requested
directory, and false if not.
Example 1
chdir(/usr/bin/perl) || die cannot change directory :$!);
Changing Directory
Example 2
Print Enter directory to change to ?;
chomp ($where = <STDIN>);
If (chdir($where)) {
Print new directory is $where;
} else {
print cannot change to $where;
}
The chdir function without parameter defaults to your home directory.
Globbing
Asterisk (*) is the wild card char used to indicate a list of files.
The expansion of * into a list of matching filenames is called globbing.
Like /etc/host* means all files that begin with host in the /etc directory.
Perls globbing is by putting the * in a pair of angled brackets or to use the
function glob.
Ex.
@a = </etc/host*>;
@a = glob(/etc/host*);
The glob returns a list of all names that match a pattern or an empty list.
Globbing
Ex.
To look at one name at a time;
While ( defined($nextname = <C:\\Training\\*>)) {
Print listed file is $nextname\n;
# dir path is included in
$nextname
$nextname =~ s/.*\\//;
# removes part before last
back slash
print listed file is $nextname\n;
# only name is printed
}
glob function can have multiple patterns inside, which are constructed separately and
finally concatenated as one list.
@fred_barney_files = <fred* barney*>;
Globbing
Ex.
If (-d /usr/etc) {
} else {
$where = /etc;
}
@files = <$where/*>;
Directory Handles
If your OS provides the readdir library function, or its equivalent, perl provides
access to it using directory handles.
Directory handles are names in separate namespace and have the same general
restrictions.
Thus a filehandle FRED and a directory handle FRED are unrelated.
The directory handles is a connection to a particular directory which you use to
read a list of filenames within the directory.
Directory handles are read only.
Note : if your OS does not support readdir, then action with directory handle will result
in a fatal error.
The opendir function takes a name for the directory handle and a string value of
the directory to open.
It returns true or false.
Ex.
opendir(ETC, /etc) || die cannot opendir /etc: $!;
To close a directory handle;
closedir(ETC);
Removing a File
Ex.
unlink (fred);
# deletes file named fred
unlink (myfile, yourfile); #deleting multiple files
unlink (*.c);
# multi files delete with wildcard
Print Enter a file name to delete !;
Chomp($name = <STDIN>);
unlink $name;
Removing a File
Ex.
Foreach $file (<*.c>)
{
# step through a list of files
unlink ($file) || warn cannot delete file $file: $!;
}
Renaming a File
The Unix mv command to rename a file is done in perl using the rename($old,
$new).
Example
rename (fred, barney) || die cannot rename fred to barney: $!;
rename(file, some-dir/file);
Similar to the Unix mkdir command to create a directory, Perls equivalent is also
mkdir function.
Perls mkdir function takes the name of the directory and mode for the
permissions of the directory to be created.
Ex.
mkdir (mydir, 0777) || die cannot create directory mydir: $!;
The Unix command rmdir to remove a directory, is the same name used in perl
as a function.
Ex.
Rmdir (mydir)|| die cannot remove directory mydir: $!;
Modifying Permissions
Ex.
chmod (0666, fred, barney); #makes files fred and barney
read/write for all
Modifying Permissions
The chown function is used to change the owner and group and works in the
same manner as unlink and chmod.
The chown takes as parameters for UID, GID, and files names.
Ex.
Chown (1234, 35,fred,barney); # changes files fred and
# barney to belong to
# uid 1234 of group 35.
References
References are like Pointers in C
A Reference is a Scalar Variable that holds the address of a Variable
or Function
There are various ways to Create References in Perl
Using the \ operator
Creating a reference to an unnamed Array
Creating a reference to an unnamed Hash
Creating a reference to an unnamed Subroutine
Creating a reference to an unnamed Scalar
References
USING THE \ OPERATOR
$a = 10;
$scalar_ref = \$a;
References
CREATING A REFERENCE TO AN UNNAMED ARRAY
$array_ref = [1, 2, 3, 4];
$new_ref = []
# Ref to an empty Array
CREATING A REFERENCE TO AN UNNAMED HASH
$hash_ref = {1, 2, 3, 4, 5};
$new_ref = {}
# Ref to an empty Hash
References
CREATING A REFERENCE TO AN UNNAMED SUBROUTINE
$sub_ref = sub # Same here. No SubName given. Just a Ref.
{
print "Hello World" ;
}
CREATING A REFERENCE TO AN UNNAMED SCALAR
$scalar_ref = \"Hello World";
THIS IS A CONSTANT IN PERL
Using a Reference
Scalar
$a = 10;
$scalar_ref = \$a;
print($$scalar_ref);
Array
@arr = (1, 2, 3, 4);
$array_ref = \@arr;
print(@$array_ref);
The First @ stands for De-reference as an ARRAY
Using a Reference
Hash
%hash = ("Apples", 10, "Bananas", 20);
$hash_ref = \%hash;
print(%$hash_ref);
The First % stands for "Deref as a HASH
Subroutine
$sub_ref = \&mySub;
# Gives a Ref to mySub
&$sub_ref("Hello", "World");
# The & stands for "Deref as CODE
sub mySub {
($a, $b) = @_;
# 2 parameters
print("$a, $b");
}
Objects
Objects are Special Modules and Modules in turn are Reusable
Packages
The idea of Packages comes from the implementation of Symbol
Tables in Perl
A Symbol Table of a Perl Program contains a list of all Global
Variables and 'Functions' Declared or Defined in the Program
Symbol Table
Each Package in Perl has its own Private Symbol Table
The Default Package is main and its Symbol Table is available
This shifts the context of your application to the new package and
Symbol Table
foreach $element(keys %main::)
{
print "$element \n";
# Will print all the Symbols available.
}
Creating Modules
Reusable Packages are Created through Perl Modules
Perl Modules are .pm files with the same name as the Package
package myPackage;
SAVE THE FILE AS myPackage.pm AND YOU HAVE A PERL MODULE
In this module you can create Variables and Subroutines which can then be
Creating Modules
# myModule.pm
package myModule;
require Exporter; # Need Exporter Module to help Export Symbols
@EXPORT = ('$sally', 'mySub'); # No var Substitution here!!
@EXPORT_OK = ('$harry');
@ISA = (Exporter);
$sally = 'Met Harry';
$harry = 'Met Sally';
sub mySub {
print("When Harry met Sally");
}
Module can still use the Subroutines in your Module using the
Module::subname() syntax
Moment you say require Module OR use Module
A reference of the Module's Symbol Table (Module::) is added to your
Symbol Table
Database Access
# Module DBI
# Module Win32::OLE
$ConnObj = Win32::OLE->new("ADODB.Connection");
# Create Object
$ConnObj->open(source_db_conn');
# Open Connection
$sql = "SELECT au_fname, au_lname FROM authors";
$RstObj= $ConnObj->Execute($sql);
while(!$RstObj->EOF()) {
$fname = $RstObj->Fields('au_fname')->Value();
$lname = $RstObj->Fields('au_lname')->Value();
print "$fname, $lname \n";
$RstObj->MoveNext();
}
$RstObj->close();
$ConnObj->close();
PPM GUI
Introduction
Environment
Request
The client can use GET or POST method to submit the Request
The form contents will be appended to URL in Get method
The form contents will be sent as stream to the server in POST method
If the Request method is POST then the Query String is not
Request
Response
Example
Thank You.