Upload
others
View
9
Download
0
Embed Size (px)
Citation preview
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Perl Tutorial
Erik Hjelmås
March 22, 2011
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits(OUSTERHOUT, J., “Scripting: Higher-Level Programming for the 21st Century”,
IEEE Computer, Vol. 31, No. 3, March 1998, pp. 23-30.)
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
WARNING!
The following presentation is NOT meant to be acomprehensive/complete tour of the Perl language.
The purpose is to get you started with some basic programconstructions which you will recognize based onsome-sort-of-programming-background.
At the end of the presentation you will find pointers to morecomprehensive material.
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Practice
You need a GNU/Linux distribution (e.g. Ubuntu) running ona physical or virtual machine with working access to theinternet, and with perl and wget installed.
Log in and open a terminal window, download the examplesas we go along with
wget http :// www.hig.no/~ erikh/tutorial -perl/ FILENAME
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Hello World
#!/ usr/bin/perl# hello.pl
print "Hello world !\n";
make executable and execute:
chmod +x hello.pl./ hello.pl
or direct from command line
perl -e 'print "hello world !\n";'
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Single Variables
#!/ usr/bin/perl# single -var.pl
$firstname =Mysil;$lastname = Bergsprekken ;$fullname =" $firstname $lastname ";print "Hello $fullname , may I call you $firstname ?";
Scalars start with a $
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Arrays
One-dimensional arrays:
#!/ usr/bin/perl# array.pl
@os =("linux", " windows ");$os [2]="mac";print $os [1], "\n"; # print windowsprint @os , "\n"; # print entire arrayprint $#os+1, "\n"; # length of array
Arrays start with a @
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Associative Arrays
#!/ usr/bin/perl# assoc -array.pl
%user =(" frodeh " => "Frode Haug","ivarm" => "Ivar Moe"
);$user{" lailas "}="Laila Skiaker ";print $user{"ivarm"}, "\n"; # print Ivar Moeprint %user , "\n"; # print entire arrayprint $#user , "\n"; # nonsense ! instead do:print scalar keys %user , "\n";
Associative arrays start with a %
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Structures/Classes
Perl has objects which can simulate structs:
#!/ usr/bin/perl# struct .pl
use Class :: Struct ;struct host => { os => '$',
sw => '@',user => '%' };
$spock = new host;$spock ->os("linux");$spock ->sw(["gcc", "flex", "vim"]);$spock ->user ({" frodeh " => "Frode Haug",
" monicas " => " Monica Strand "});print $spock ->os , "\n";print $spock ->sw(2), "\n";print $spock ->user(" monicas "), "\n";
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Command-Line Arguments
All command-line arguments in @ARGV
Scriptname in $0, arguments in $ARGV[0], $ARGV[1], ...
#!/ usr/bin/perl# cli -args.pl
print "I am $0 , and have ", $# ARGV +1," arguments first is $ARGV [0]\n";
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Input From User
#!/ usr/bin/perl# input -user.pl
print "Say something here: ";$something =<STDIN >;print "you said $something ";
The operator <FD> reads one line (or more dependent onthe context, more on that in a few slides) from thefiledescriptor FD
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Input From STDIN
Same way, commonly without a print first
#!/ usr/bin/perl# input -stdin.pl
$something =<STDIN >;print "you said $something ";
can be executed as
echo "hey hey!" | ./ input -stdin.pl
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Context Dependent OperatorsThe operator <...> in scalar context
#!/ usr/bin/perl# context - scalar .pl
$array = <STDIN >;print $array ;
will read one line, while in array context will read an entirearray
#!/ usr/bin/perl# context -array.pl
@array = <STDIN >;print @array ;
So, some operators behave differently in scalar and arraycontext.
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Input From Files or Pipes
#!/ usr/bin/perl# input -files -pipes.pl
open(FD ,"<hello.pl") || die ("hello.pl: $!");@fil=<FD >; # array contextprint @fil;close(FD);
# or open a file descriptor to a pipe
open(FD ,"ls -1 |") || die ("ls -1: $!");@fil=<FD >; # array contextprint @fil;close(FD);
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Input from System Commands
#!/ usr/bin/perl# input - commands .pl
$kernel =`uname -sr `;chomp $kernel ;print "I am running on $kernel in ",`pwd `;
chomp removes linebreak (\n on Unix/Linux, \r\n onWindows), commonly used when input read with <FD>(where FD is a file descriptor)
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
if/else
#!/ usr/bin/perl# if.pl
if ($# ARGV +1 != 1) {print "usage: $0 <argument >\n";
}
can also be written as
#!/ usr/bin/perl# if -short.pl
print "usage: $0 <argument >\n" if ($# ARGV +1 != 1);
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Numeric Comparison
Operator Meaning< Less than> Greater than<= Less than or equal to>= Greater than or equal to<=> Comparison== Equal to!= Not equal to
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
String Comparison
Operator Meaninglt Less thangt Greater thanle Less than or equal toge Greater than or equal tocmp Comparisoneq Equal tone Not equal to
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
File Tests
Operator Meaning-e Exists-s Not zero size-f Regular file-d Directory-l Symbolic link-u Set-user-id (SetUID) flag set
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Boolean
Operator Meaning! Not&& And|| Or
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Numerical or String Compare
#!/ usr/bin/perl# if -num - string .pl
if ($# ARGV +1 != 2) { # numerical cmpprint "usage: $0 <argument > <argument >\n";exit 0;
} elsif ($ARGV [0] == $ARGV [1]) { # numerical cmpprint "$ARGV [0] is arithm . equal to $ARGV [1]\n";
} else {print "$ARGV [0] and $ARGV [1] arithm . differs \n";
}if ($ARGV [0] eq $ARGV [1]) { # string cmp
print "$ARGV [0] is string equal to $ARGV [1]\n";} else {
print "$ARGV [0] and $ARGV [1] string differs \n";}print "$ARGV [0] is also a file\n" if (-f $ARGV [0]);
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Boolean example
#!/ usr/bin/perl# if -bool.pl
if ((1==2) && (1==1) || (1==1)) {print "And has precedence \n";
} else {print "Or has precedence \n";
}
# force OR precedence :
if ((1==2) && ((1==1) || (1==1))) {print "And has precedence \n";
} else {print "Or has precedence \n";
}
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Switch/Case
#!/ usr/bin/perl# switch .pl
use Switch ;%short = ( yes => "y", nope => "n" );$ans = <STDIN >;chomp $ans;switch ($ans) {
case m/yes/ { print "yes !\n"; next; }case m/nope/ { print "nope !\n"; }case (% short) { print " $short {$ans }\n"; }print "$ans ???\n";
}
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
For loop#!/ usr/bin/perl# for.pl
for ($i =1;$i <=3; $i ++) {print "$i\n";
}
# something more useful :
@file=`ls -1`;for ($i =0;$i <=$# file;$i ++) {
chomp $file[$i];if (-f $file[$i]) {
print "$file[$i] is a regular file\n";} else {
print "$file[$i] not regular file\n";}
}
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Foreach loop
#!/ usr/bin/perl# foreach .pl
foreach $i (`ls -1`) {print "$i";
}
# with associative arrays :
%user =(" frodeh " => "Frode Haug"," monicas " => " Monica Strand ","ivarm" => "Ivar Moe"
);foreach $key (keys %user) {
print "$user{$key }\n";}
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
While
We want to read from STDIN and do stuff line by line
#!/ usr/bin/perl# while.pl
# This is myscript .pl$i =0;while(<STDIN >) {
chomp;$foo[$i]=$_;$i ++;
}print "size of foo " ,$# foo +1,"\n";
$ ls -1 | ./ myscript .plsize of foo is 20
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Operators
Operator Meaning+ Add- Subtract* Multiply/ Divide% Modulus** Exponent
#!/ usr/bin/perl# math.pl
print "3+5 is " ,3+5,"\n";
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Functions
#!/ usr/bin/perl# func.pl
# declare :sub add {
my ($a , $b) = @_;print "$a+$b is ",$a+$b ,"\n";
}# use:add (5.12 ,2.56);
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Regular expressions intro 1/5
Special/Meta-characters:
\ | ( ) [ ] { } ^ $ * + ? .
These have to be protected with \, e.g.http://www\.hig\.no
To match c:\temp, you need to use the regexc:\\temp. As a string in C++ source code, thisregex becomes "c:\\\\temp". Four backslashesto match a single one indeed.
(from http://www.regular-expressions.info/characters.html):
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Regular expressions intro 2/5
Describing characters:
Operator Meaning. Any single character
[abcd] One of these characters[^abcd] Any one but these characters
[a-zA-Z0-9] A character in these ranges\w, \W A word, A not-word character\d, \D A digit, A not-digit character
\b A word boundary
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Regular expressions intro 3/5
Grouping:
Operator Meaning() Group| OR
Anchoring:
Operator Meaning^ Beginning of line$ End of line
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Regular expressions intro 4/5
Repetition operators/Modifiers/Quantifiers:
Operator Meaning? 0 or 1 time* 0 or more times+ 1 or more times
{N} N times{N,} At least N times{N,M} At least N but not more than M
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Regular expressions intro 5/5
Finding URLs in HTML:(mailto|http)://[^"]*
Each line should be an email address:^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+$
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Perl example
#!/ usr/bin/perl# regexp .pl
while(<STDIN >) {chomp;if (m/^([A-Za -z0 -9._ -]+@([A-Za -z0 -9. -]+))$/) {
print "Valid email $1\n";print " Domain is $2\n";
} else {print " Invalid email address !\n";
}}
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Advanced stuff
See Comprehensive Perl Archive Network (CPAN) at
http://www.cpan.org
for everything you can do with Perl
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Let’s solve this together
Write a script which
• reads urls from STDIN (typically piped into this script,one url on each line)
• retrieves the document located at the url• searches the document line-by-line with a regexp
supplied on the command line• output nicely formatted relevant info if matches found
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Getting started
1 <loop: lines in urlfile>2 <retrieve urls to files>1 <end loop>
1 <loop: files>3 <loop: lines in each file>3 <if match>4 <nice output>3 <end loop>1 <end loop>
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Nice Script, but ...
Is the script efficient?
• time it, analyze its resource usage (I/O usage?)
Is the script secure?
• how will it be used? system program with privileges?• input validation?• what are its powers?• how can it fail?
Perl Tutorial
Erik Hjelmås
VariablesArrays
Structures/Classes
Command-line args
InputInput
System commands
Conditionsif/else
Operators
Switch/case
IterationFor
Foreach
While
Math
Functions
RegExpPerl example
Perl only
Case
Credits
Credits
http://www.cpan.org/T. Christiansen, R. L. Schwartz and L. Wall, "Programming Perl, Second Edition",O’Reilly Media, 1996.http://www.misc-perl-info.com/http://www.cs.cf.ac.uk/Dave/PERL/http://www.perl.orghttp://www.tutorialspoint.com/perl/J. Ousterhout, "Scripting: Higher-Level Programming for the 21st Century," IEEEComputer, Vol. 31, No. 3, March 1998, pp. 23-30.Jon Thingvold’s “Drift av flerbrukersystemer”, kompendium 1999.http://www.regular-expressions.info/