PerlPractical Extraction and Report Language
ObjectivesIntroductionBasic featuresVariablesOperators and functionsControl structuresInput and output
Perl is a script languageElements of csh, sh, awk and CUsed for:Text manipulationCGI scriptingSystem administrationWritten and maintained by Larry WallWebsiteswww.perl.comwww.perl.org www.perldoc.comwww.perlfoundation.org www.cpan.orgIntroduction to Perl
Example:#! /usr/bin/perl# example of perl scriptprint hello world\n;print(hello world\n);printf(hello world\n);printf(%s\n, hello world);Introduction to Perl
VariablesScalarSingle valuedArrayIndexed collection of valuesHashCollection of key, value pairs
Scalar Variablesstring$word = test;print here it is: $word \n;
quotes around string optional, if clear$word = test;print here it is $word \n;
Scalar Variablesinteger
$i = 2;print $i;print $i\n;
$j = 2 * $i + 4;
printf(Result %d \n, $j);print Result $j \n;
Scalar Variablesfloating point
$f = 1.234;$g = 2 * $f + 4;
printf("Result %f\n", $g);print "Result $g\n";
Reading Inputfrom Standard input
print("enter a number: ");$number = ;chop($number);print("here it is: $number \n");
Array VariablesArray holds list:
("one", "two", "three")(1, 4, 5, 7, 8, 0)(1.2, 4.3, 6.5)(one, 2, 3.14159)($word, $i, $f)
Array Variablesarray variable starts with @
@list=("one", "two", "three");print @list \n;
array element starts with $
print("here it is: $list[0]\n");print("here it is: $list[1]\n");print("here it is: $list[2]\n");
Array Variablesarray slice
@list=("one", "two", "three, 4);@a = @list[1..3];@b = @list[2,0];
or:@c = ("one", "two", "three, 4)[2,0]
Array Variablesassignment
($first, $second) = (one, two);@list = ($first, $second);($o1, $o2) = @list;
array size$size = @array;highest array index$#array
Array Variablesexample: swap two variables
$temp = $first;$first = $second;$second = $temp
better:($first, $second) = ($second, $first);
Array functionsto remove element from frontshift @array;to remove element from backpop @array;to reverse elementsreverse @array;to sort elementssort @array;
VariablesHash: associative array
%animals = ("cat => 10, "dog => 12, "fish => 23);print("1: $animals{'cat'}\n");print("2: $animals{'dog'}\n");print("3: $animals{'fish'}\n");
Hash variable operation%animals = ("cat => 10, "dog => 12, "fish => 23);%index = reverse %animals;print("1: $index{10'}\n");print("2: $index{12'}\n");print("3: $index{23'}\n");
Hash variable operation%animals = ("cat => 10, "dog => 12, "fish => 23);@names = keys %animals;@numbers = values %animals;
Special VariablesDefault parameter: $_
Used by many operations when no parameters are given
Example:$_ = hello world\n;print;
Command line arguments$ARGV[0], $ARGV[1],
print("$ARGV[0], $ARGV[1]\n");
With a loop:$size = @ARGV;for ($i = 0; $i < $size; $i++){ print("$ARGV[$i]\n");}
Environment variables%ENV hash
examples:
print $ENV{HOME};print $ENV{PATH};$ENV{EDITOR} = emacs;
Operatorsnumeric: + - * / % ++ --boolean: && || !and or not& | ^string: .xexamples:$a = foo . bar;$b = number . 1;$c = 1 . 2;$d = ba . (nax4);$e = 1 x 3;
String functionsremove last character:chopremove last character, if it is \n:chomp
$a = foobar\n;print chop(a);print chomp(a);
String function: splitsplit string into wordsneeds word separatorexample:
$test = one two three;@list = split , $test;print @list\n;
String function: splitsplit with no parameters will split $_ on whitespace
example:
$_ = one two three;print split;
String function: splitword separator examples:split on string:split on regular expression/e.e//[abc]/
String function: joinopposite of split:
@list = (one, two, three);$text = join ?, @list;
String function: substrmanipulate substring
$string="the glistening trophies"; print substr($string, 15); # trophies print substr($string, -3); # ies print substr($string, -18, 9); # listening print substr($string, 4, 4); # glis
substr($string, 7, 4, "tter"); # Returns "sten" print $string; # the glittering trophies
substr($string, 7, 4) ="tter"; # Functions as lvalue
Control Structuressequence:run until end of fileexit and dieconditional:if-then-else, unlessloops:forwhilefunctions
Sequenceall statements are terminated with semicolonto end executionexit;to end with error messagedie(it was the food);to just print a warning (without exiting)warn(it is too warm in here);
Conditionalif
if ( $i > 10 ) {print yes\n;} else {print no\n;}
Conditionalunless
unless ( $i > 10 ) {print no\n;} elseprint yes\n;}
Conditionalone liners:
print no\n unless ( $i > 10 );
print yes\n if ( $i > 10 );
die(unhappy) unless ( $happy > 0);
LoopsC-like for loop:
for ($i=0; $i
Loopsfor arrays:
@array = (one, two, three);foreach (@array) {print value is $_ \n;}
Loopswhile:
$i=10;while ($i > 5) {print value is $i \n;$i--;}
Loopsspecial keywords within while:
next skip to next iterationlastend loopredorerun iteration
Pattern matchingPerl supports regular expressionsbasic and extendedenclosed in forward slash /match operator =~return boolean true or false
$sea = water sand jaws swimmers;print Shark Alert ! if $sea =~ /jaws/;
Pattern matchingspecial characters:\w - word\W - non word\s - space\S - non space\d - digit\D - non digit\b - word boundary
Pattern matchingpattern may include parenthesis ()identifies matched junks as $1, $2, $3
$sea = water sand jaws swimmers;print Shark Alert ! if $sea =~ /(j??s)/;print $1;
Pattern substitution
$test = he said she said;$test =~ s/said/did/;
Sub-functions example:
sub greeting {print hello world\n;} greeting();
Sub-functions parameters are passed via @_ array:
sub action {($one, $two, $three) = @_;warn too few parameters unless $one && $two && $three;print The $one $two on the $three\n;} action(cat, sat, hat);
Sub-functions return results via return:
sub action {($one $two $three) = @_;warn too few parameters unless $one && $two && $three;return The $one $two on the $three\n;} print action(cat, sat, hat);
Sub-functions local variables: visible only with scope of sub-function
sub getwords {my pat = $_[0];my ($line, @subwords);$line = ;chop($line);@subwords = split /$pat/, $line;return @subwords;}
Reading Inputfrom Standard input
print("enter a number: ");$number = ;print("here it is: $number");
Reading Inputfrom Standard input
$i = 0;while ($line = ) {print $line;$i++;}print(line count: $i \n");
File I/Obased on file handlepredefined file handlesSTDINSTDOUTSTDERR
print STDERR oohh, something went wrong !\n;
File I/Oto create new file handle open fileopen filehandle filename;filename can be:filefile>>file
ls||wc
Reading from a File
if (!open(FILE, "$ARGV[0]")) { print "cannot open: $ARGV[0]\n ;}while ($line = ) { print "$line ;}
Reading complete File
die horribly unless open FILE t.txt;@all = ;$linecount = @all;print line count: $linecount;
Writing to a File
die "cannot open: $ARGV[0] unless open FILE, >$ARGV[0]
@array = (one, two, three);foreach (@array) { print FILE $_ \n;}
Running system commandsvia backquotes ` `$result = `ls | wc w`
via system function$result = system(ls | wc w);
via file I/Oopen FILE, ls | wc w|;$result = ;
Running system commands#!/usr/local/bin/perl# convert series of files from DOS to Unix format
if ($#ARGV < 0) { print "usage: fconvert files\n"; exit;}foreach (@ARGV) { $cmd = "dos2unix $_ $_.unix"; print "$cmd\n"; if(system($cmd)) { print "dos2unix failed\n"; }}
Perl modulescontain large amounts of reusable codeCPAN: Comprehensive Perl Archive Networknetworkingweb relatedcgi processingdatabase accessspam protection
Web & CGIHTML may include forms to invoke server side functionsCGI (Common Gateway Interface) is a protocol governing how browsers and servers communicateScripts that send or receive information need to follow the CGI protocolPerl is the most commonly used language for CGI programmingPerl scripts are written to get, process, and return information through Web pages
Html via Perl
#! /usr/local/bin/perlprint Content-type: text/html\n\n;print Hello World;print \n;print Test Website";print ;
Html via PerlCGI module:
use CGI qw(:standard);print(header);print(start_html("Hello World"));print h2("Test Website");print(end_html);
Web Page
COP 3344
User Inquiry
Enter your name:
Interactive Web Page
Perl script: example.cgi#! /usr/local/bin/perl# example perl scriptuse CGI qw(:standard);print(header);print(start_html("Anser Page"));print h2("Answer Page");print("Welcome: ", param('userid'));print(end_html);
Interactive Web Page
Chapter SummaryPerl is a powerful scripting languagePerl scripts are used to create web pagesCGI is a protocol or set of rules governing how browsers and servers communicate