practical extraction and report language perl - vital-it · perl's cgipm module, part of...
TRANSCRIPT
Page 1VI, October 2006
Practical Extraction and Report Language
« Perl is a language of getting your job done »
Larry Wall
« There is more than one way to do it »
Page 2VI, October 2006
Perl
History
Structure of a simple Perl script
Perl variables
scalar ($)
array (@)
hash (%)
Operators (numeric, string & logical)
Statement modifiers (if/elsif/else, for/foreach, while)
Outline :
Page 3VI, October 2006
Practical Extraction and Report Language
http://perl.oreilly.com
" Perl is both a programming language
and an application on your computer that runs those programs "
Page 4VI, October 2006
Perl history
1969 UNIX was born at Bell Labs.
1970 Brian Kernighan suggested the name "Unix" and the operating
system we know today was born.
1972 The programming language C is born at the Bell Labs
(C is one of Perl's ancestors).
1973 “grep” is introduced by Ken Thompson as an external utility:
Global REgular expression Print.
1976 Steven Jobs and Steven Wozniak found Apple Computer (1 April).
1977 The computer language awk is designed by Alfred V. Aho, Peter J.
Weinberger, and Brian W. Kernighan (awk is one of Perl's ancestors).
A few dates:
Page 5VI, October 2006
Perl history
1987 Perl 1.000 is unleashed upon the world
NAME perl | Practical Extraction and Report Language
SYNOPSIS perl [options] filename args
DESCRIPTION Perl is a interpreted language optimized for scanning arbitrary text
files, extracting information from those text files, and printing reports based on that
information. It's also a good language for many system management tasks. The language
is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny,
elegant, minimal). It combines (in the author's opinion, anyway) some of the best features
of C, sed, awk, and sh, so people familiar with those languages should have little difficulty
with it (Language historians will also note some vestiges of csh, Pascal, and even
BASIC|PLUS). Expression syntax corresponds quite closely to C expression syntax. If
you have a problem that would ordinarily use sed or awk or sh, but it exceeds their
capabilities or must run a little faster, and you don't want to write the silly thing in C, then perl
may be for you. There are also translators to turn your sed and awk scripts into perl scripts
OK, enough hype.
Page 6VI, October 2006
Perl history
1994 Perl5: last major release (Currently Perl 5.8.6).
1996 Creation of the CPAN repository of modules and documentation
( Comprehensive Perl Archive Network).
2006 Perl 5.8.8
Supported Operating Systems:
Unix systems / Macintosh (OS 7-9 and X) / Windows / VMS
Perl Features
Perls database integration interface (DBI) supports thirdparty databases
including Oracle, Sybase, Postgres, MySQL and others.
Perl works with HTML, XML, and other markup languages .
Perl supports Unicode.
Perl is Y2K compliant.
Perl supports both procedural and objectoriented programming.
Perl interfaces with external C/C++ libraries through XS or SWIG.
Perl is extensible There are over 500 third party modules available from
(CPAN).
Page 7VI, October 2006
Perl history
Perl and the Web
Perl is the most popular web programming language due to its text
manipulation capabilities and rapid development cycle.
Perl's CGIpm module, part of Perl's standard distribution, makes handling
HTML forms simple.
Perl can handle encrypted Web data, including ecommerce transactions.
Perl can be embedded into web servers (mod_perl) to speed up processing
by as much as 2000%.
Perl's DBI package makes webdatabase integration easy.
Page 8VI, October 2006
Perl Hello world !
My first program (hello.pl) :
pcX: vioannid$ which perl
/usr/bin/perl
pcY: vioannid$ which perl
/usr/local/bin/perl
#!/usr/local/bin/perl
use strict;
use warnings;
#tell the program to print "Hello world"
print "Hello world" ;
#tell the program to exit
exit ;
The first line of a Perl program is called "command interpretation" or "Shebang line". This line
refers to the "#!" and tells the computer that this is a Perl program.
To find out whether you should use /usr/bin/perl OR /usr/local/bin/perl,
type: "which perl" in your shell:
Page 9VI, October 2006
Perl Hello world !
My first program (hello.pl) :
computerX: vioannid$ which perl
/usr/bin/perl
computerY: vioannid$ which perl
/usr/local/bin/perl
#!/usr/local/bin/perl
use strict;
use warnings;
#tell the program to print "Hello world"
print "Hello world" ;
#tell the program to exit
exit ;
perl script
UNIX shell
[embnet01@bc2-linux3 ~]$ which perl
/import/bc2/soft/bin/perl5/perl
#!/import/bc2/soft/bin/perl5/perl
Page 10VI, October 2006
Perl Hello world !
My first program (hello.pl) :
use strict;
A command like use strict is called a pragma. Pragmas are instructions to the Perl interpreter to do
something special when it runs your program. "use strict" does two things that make it harder to
write bad software:
It makes you declare all your variables, and
it makes it harder for Perl to mistake your intentions when you are using subroutines
ALL STATEMENTS END IN A SEMICOLON ";"
(similar to the use of the period "." in the English language)
#!/usr/local/bin/perl
use strict;
use warnings;
#tell the program to print "Hello world "
print "Hello world" ;
#tell the program to exit
exit ;
Page 11VI, October 2006
Perl Hello world !
My first program (hello.pl) :
#!/usr/local/bin/perl
use strict;
use warnings;
#tell the program to print "Hello world"
print "Hello world" ;
#tell the program to exit
exit ;
use warnings;
Comments are good, but the most important tool for writing good Perl is the "warnings". Turning on
warnings will make Perl yelp and complain at a huge variety of things that are almost always
sources of bugs in your programs.
Perl normally takes a relaxed attitude toward things that may be problems:
it assumes that you know what you're doing, even when you don't…
Page 12VI, October 2006
Perl Hello world !
My first program (hello.pl) :
#!/usr/local/bin/perl
use strict;
use warnings;
#tell the program to print "Hello world"
print "Hello world" ;
#tell the program to exit
exit ;
Comments
All lines starting with "#" are not taken into account in the execution of the program.
Good comments are short, but instructive. They tell you things that aren't clear from reading
the code.
Blank lines or spaces are also not taken into account in the execution of the program. However, they
help in the reading of the code.
Page 13VI, October 2006
Perl Hello world !
My first program (hello.pl) :
#!/usr/local/bin/perl
use strict;
use warnings;
#tell the program to print "Hello world"
print "Hello world" ;
#tell the program to exit
exit ;
Print statement:
… prints !
By default, the standard output is the shell window from which the program is executed.
ALL STATEMENTS ENDS IN A SEMICOLON ";"
(similar to the use of the period "." in the English language)
Page 14VI, October 2006
Perl Hello world !
My first program (hello.pl) :
#!/usr/local/bin/perl
use strict;
use warnings;
#tell the program to print "Hello world"
print "Hello world" ;
#tell the program to exit
exit ;
The exit statement:
Tells the computer to exit the program.
Although not explicitely required in Perl, it is definitely common.
Page 15VI, October 2006
Perl Hello world !
My first program (hello.pl) :
#!/usr/local/bin/perl
use strict;
use warnings;
#tell the program to print "Hello world"
print "Hello world" ;
#tell the program to exit
exit ;
Do not forget to make the file executable:
output:
vioannid$ ./hello.pl
Hello worldvioannid$
vioannid$ chmod a+x hello.pl
Page 16VI, October 2006
Perl Hello world !!
Print :
#!/usr/local/bin/perl
use strict;
use warnings;
#play with the print statement
#words separated by newline
print "Hello\nworld\n" ;
#words separated by tabs & a final newline
print "Hello\tworld\n" ;
#usage of the period to cat strings
print "Hello"."world"."\n";
#tell the program to exit
exit ;
vioannid$ ./hello2.pl
Hello
world
Hello world
Helloworld
vioannid$
Important:
Unix & all Unix flavors: \n
Mac OS : \r
Windows: \r\n
Page 17VI, October 2006
Perl variables and data types
Type Character Example Is a name for:
Scalar $ $gene_symbol An individual value (number or string)
Array @ @sequences A list of values, keyed by number
Hash % %descriptions A group of values, keyed by string
Subroutine & &align A callable chunk of Perl code
Typeglob * *protein Everything named protein
Variables are containers which can hold data of a various types
Page 18VI, October 2006
Perl variables - Scalars
scalars
a single string (of any size, limited only by the available memory), or
a number (integers, floating-point numbers), or
a boolean (true or false or 0 or 1), or
a reference to something
The “beauty” of PERL is that you don’t declare your scalar variables to be of a certain data type,
Perl figures it out for you ! Depending on the CONTEXT, Perl will automatically interpret them as
strings, as numbers, or as boolean values (true or false).
Scalar values are always named with '$' (even when referring to a scalar that is part of an array or
a hash). The '$' symbol works semantically like the English word "the" in that it indicates a single
value is expected.
my $variable_1 = "Hello world !\n"; #note the quotes
my $variable_two = 30; #note the absence of quotes
Page 19VI, October 2006
Perl variables - Scalars
Numeric
my $pi = 3.14159; # floating point number
my $avogadro = 6.02e23; # scientific notation
my $cash = 33651235421; # huge integer
my $cash2 = 33_651_235_421; # huge integer with underlines for visibility
my $result = 25; # integer
Numeric operators
1 + 1 # 1 plus 1, or 2
2.5 - 1.5 # 2.5 minus 1.5, or 1
2 * 6 # 2 times 6, or 12
14 / 2 # 14 divided by 2, or 7
10.2 / 3.14159 # 10.2 divided by 3.14159, or 3.24676358149854
10 % 3 # 10 modulo 3, or 1
10 / 3 # 10 divided by 3, or 3.333333333 (ALWAYS floating-point)
2 ** 3 # 2 to the power 3, or 8
my $total = $result + $cash2; # $total has now the value: 33651235446
Page 20VI, October 2006
Perl variables - Scalars
Strings (sequences of characters)
' … ' (or q//) #no variable and backslash interpolation
my $name = 'Vassilios'; #literal string
my $hello = 'hello\tsir!'; #if printed, outputs: hello\tsir
my $cost = 'The meeting costs $100' ; #if printed, outputs: The meeting costs $100
my $good_guy = '$name is a good guy!' #if printed, outputs: $name is a good guy!
" … " (or qq//) #variable and backslash interpolation
my $hello = "hello\tsir!"; #if printed, outputs: hello sir
my $good_guy2 = "$name is a good guy!" #if printed, outputs: Vassilios is a good guy!
Double-quoted string escapes:Construct Meaning
\n newline
\r return
\t tab
\\ backslash
\" double quote \$, \@, \& etc…
Page 21VI, October 2006
Perl variables - Scalars
#!/usr/bin/perl
use strict; use warnings;
my $pet_string = "This is to TEST\nsome string functions";
print $pet_string;
# lc returns lowercased version of $pet_string
my $lc_string = lc($pet_string);
print $lc_string;
# uc returns uppercased version of $pet_string
my $uc_string = uc($pet_string);
print $uc_string;
# length returns the length of $pet_string
my $length_string = length($pet_string);
print "$length_string";
print "*"x10;
print "\t".("*"x10)."\n";
exit;
Important strings functions I
This is to TEST
some string functions
this is to test
some string functions
THIS IS TO TEST
SOME STRING FUNCTIONS
38
********** **********
Page 22VI, October 2006
Perl variables - Scalars
#!/usr/bin/perl
my $pet_string = "TEST of some\nstring functions\n";
print $pet_string;
# reverses $pet_string (character by character)
my $rev_string = reverse($pet_string);
print $rev_string."\n";
# takes 3 arguments: string value, zero-based
# initial position and length for the substring
my $sub_string = substr ($pet_string,0,15);
print $sub_string."\n";
# if a string ends in a newline character, chomp removes it
my $chomp_string = $pet_string;
print $chomp_string; chomp($chomp_string);
print $chomp_string;
# chop removes the last character of a string
my $chop_string = $chomp_string;
print $chop_string; chop($chop_string); print $chop_string;
exit;
Important strings functions II
TEST of some
string functions
snoitcnuf gnirts
emos fo TSET
TEST of some
TEST of some
string functions
TEST of some
string functions
TEST of some
string functionsTEST of some
string functionsTEST of some
string functionvioannid$
Page 23VI, October 2006
Perl variables - Arrays & Hashes
Multivalued Data Structures:
0 1 2 3
car bike van plane
@locomotion
%days
Mon
Monday
Tue
TuesdayWed
Wednesday
Thu
Thursday
Fri
Friday
Sat
Saturday
Sun
Sunday
Page 24VI, October 2006
Perl variables - Arrays
#!/usr/bin/perl
# array of strings
my @string_numbers = ('One', 'Two', 'Three', 'Four');
print @string_numbers;
print "\n";
# array of integers
my @numeric_numbers = (1..5);
print "@numeric_numbers\n";
my @numeric_numbers2 = (1,2,3,4,5);
print "@numeric_numbers2\n";
print "$string_numbers[2]\n";
exit;
arrays I
Normal arrays are ordered lists of scalars indexed by number (starting with 0).
Entire arrays are denoted by '@', which works much like the word "these" or "those" does in
English, in that it indicates multiple values are expected.
OneTwoThreeFour
1 2 3 4 5
1 2 3 4 5
Three
Page 25VI, October 2006
Perl variables - Arrays
#!/usr/bin/perl
# array of strings
my @string_numbers = ('One', 'Two', 'Three', 'Four');
# replaces One with Zero in @string_numbers
$string_numbers[0] = 'Zero';
print "@string_numbers\n";
my @sort_string_numbers = sort @string_numbers;
print "@sort_string_numbers\n";
print scalar @string_numbers;
print "\n";
my $nb = @string_numbers;
print "$nb\n";
exit;
arrays II
Zero Two Three Four
Four Three Two Zero
4
4
Page 26VI, October 2006
Perl variables - Arrays
#!/usr/bin/perl
my @string_numbers = ('Zero', 'Two', 'Three', 'Four');
my $end = $string_numbers[$#string_numbers];
print "$end\n";
# swap values
($gene1, $gene2) = ($gene2, $gene1);
# variable interpolation
my @login = ("$username", "$password");
my @anyarray = (6, "hello", @string_numbers );
my @rev_anyarray = reverse @rev_anyarray;
print "@anyarray\n";
print "@rev_anyarray\n";
exit;
arrays III
Four
6 hello Zero Two Three Four
Four Three Two Zero hello 6
Page 27VI, October 2006
Perl variables
Some arrays functions:
sort sorts all the elements of an array.
reverse inverses the order of all the elements of an array.
shift, unshift takes the first element, places an element at the first position of the array.
pop, push takes the last element, places an element at the last position of the array.
A B C D E F
Page 28VI, October 2006
Perl variables
ABCDEF
Some arrays functions:
sort sorts all the elements of an array.
reverse inverses the order of all the elements of an array.
shift, unshift takes the first element, places an element at the first position of the array.
pop, push takes the last element, places an element at the last position of the array.
Page 29VI, October 2006
Perl variables
ABCDE
F
F
Some arrays functions:
sort sorts all the elements of an array.
reverse inverses the order of all the elements of an array.
shift, unshift takes the first element, places an element at the first position of the array.
pop, push takes the last element, places an element at the last position of the array.
Page 30VI, October 2006
Perl variables
BCDEF
A
A
Some arrays functions:
sort sorts all the elements of an array.
reverse inverses the order of all the elements of an array.
shift, unshift takes the first element, places an element at the first position of the array.
pop, push takes the last element, places an element at the last position of the array.
Page 31VI, October 2006
Perl variables - Arrays & Hashes
Multivalued Data Structures:
0 1 2 3
car bike van plane
@locomotion
%days
Mon
Monday
Tue
TuesdayWed
Wednesday
Thu
Thursday
Fri
Friday
Sat
Saturday
Sun
Sunday
Page 32VI, October 2006
Perl variables
hashes (associative arrays of scalars)
Hashes are unordered collections of scalar values indexed by their associated string key.
Entire hashes are denoted by '%'
TyrTAT
CysTGT
SerTCT
PheTTT
ValueKey%days
Mon
Monday
Tue
TuesdayWed
Wednesday
Thu
Thursday
Fri
Friday
Sat
Saturday
Sun
Sunday
#!/usr/bin/perl
my %codon3 = (
"TTT" => "Phe",
"TTA" => "Leu",
);
print $codon3{'TTT'};
print "\n";
exit;
vioannid$ ./hash.pl
Phe
vioannid$
Page 33VI, October 2006
Perl variables
hashes (associative arrays of scalars)
Hashes are unordered collections of scalar values indexed by their associated string key.
Entire hashes are denoted by '%'
- a hash is preferably used when we want to search for something with a "name" (string)
- a hash is preferably used when we do not care what order the items are in (or easy to sort)
- a hash has no beginning or end
- hashes are very fast scalar lookup structures
- key: the string value index (must be unique!)
- value: the scalar value accessed by the key
- hash key string values cannot be altered.
(one has to insert a new key with the value from the old key and then delete the old key)
Page 34VI, October 2006
Perl variables
hashes I
#!/usr/bin/perl
my %some_hash = ("John", "Travolta", "Betty", "Bossy");
print $some_hash{"John"}."\n";
my %capitals = (
'china' => 'beijing',
'france' => 'paris',
'italy' => 'rome',
'switzerland' => 'bern',
);
print %capitals;
print "\n";
print $capitals{'china'}."\n";
my @k = keys %capitals;
my @v = values %capitals;
print "@k\n";
print "@v\n";
exit;
Travolta
switzerlandbernitalyromefranceparischinabeijing
beijing
switzerland italy france china
bern rome paris beijing
Page 35VI, October 2006
Perl variables
hashes II
#!/usr/bin/perl
my %capitals = (
'china' => 'beijing',
'france' => 'paris',
'italy' => 'rome',
'switzerland' => 'bern',
);
my $nb = keys %capitals;
print "$nb\n";
my %rev_capitals = reverse %capitals;
print %rev_capitals;
print "\n";
print $rev_capitals{'china'}."\n";
print $rev_capitals{'beijing'}."\n";
exit;
4
beijingchinabernswitzerlandparisfranceromeitaly
china
Page 36VI, October 2006
Perl - Getting User Input
How to get a value from the keyboard into a Perl program ?
The simplest way is to use the line-input operator: <STDIN>
Each time we use <STDIN> in a place where a scalar value is expected, Perl reads the next complete
text line up to the first newline from the keyboard (unless you modified it).
#!/usr/bin/perl
print "Please enter your Lastname: ";
my $lastname = <STDIN>;
print "Please enter your Firstname: ";
my $firstname = <STDIN>;
print "Hello $firstname $lastname,\n
I hope you like Perl programming !\n";
exit;
Please enter your Lastname:
Please enter your Firstname: Vassilios
Ioannidis
Hello Vassilios
Ioannidis
,
I hope you like Perl programming !
Page 37VI, October 2006
Perl - Getting User Input
How to get a value from the keyboard into a Perl program ?
The simplest way is to use the line-input operator: <STDIN>
Each time we use <STDIN> in a place where a scalar value is expected, Perl reads the next complete
text line up to the first newline from the keyboard (unless you modified it).
Please enter your Lastname:
Please enter your Firstname: Vassilios
Ioannidis
Hello Vassilios Ioannidis,
I hope you like Perl programming !
#!/usr/bin/perl
print "Please enter your Lastname: ";
my $lastname = <STDIN>;
chomp $lastname;
print "Please enter your Firstname: ";
my $firstname = <STDIN>;
chomp $firstname;
print "Hello $firstname $lastname,\n
I hope you like Perl programming !\n";
exit;
Page 38VI, October 2006
Perl operators
Perl operators
Arithmetic+ addition
- subtraction
* multiplication
/ division
Numeric comparison
== equality!= inequality
< less than
> greater than
<= less than or equal
>= greater than or equal
String comparisoneq equality
ne inequality
lt less than
gt greater than
le less than or equal
ge greater than or equal
Why do we have separate numeric and string comparisons?
Because we don't have special variable types, and Perl needs to know whether to sort
numerically (where 99 is less than 100) or alphabetically (where 100 comes before 99).
Page 39VI, October 2006
Perl operators
Perl operators
#!/usr/local/bin/perl
use strict;
use warnings;
my $x = 100;
my $y = 99;
if ($x > $y) { print "\"$x\" is numerically greater than \"$y\"\n" ; }
else { print "\"$x\" is numerically smaller than \"$y\"\n" ; }
if ($x gt $y) { print "\"$x\" is alphabetically greater than \"$y\"\n" ; }
else { print "\"$x\" is alphabetically smaller than \"$y\"\n" ; }
exit ;
vioannid$ ./string_num_comp.pl
"100" is numerically greater than "99"
"100" is alphabetically smaller than "99"
vioannid$
Page 40VI, October 2006
Perl operators
Perl operators
Boolean logic&& and
|| or
! not
Miscellaneous= assignment
. string concatenation
x string multiplication
.. range operator (creates a list of numbers)
Many operators can be combined with a "=" as follows:
$a += 1; # same as $a = $a + 1; #same as $a++;
$a -= 1; # same as $a = $a - 1; #same as $a--;
$a .= "\n"; # same as $a = $a. "\n";
Page 41VI, October 2006
Perl statement modifiers
Any simple statement may optionally be followed by a SINGLE modifier, just before the terminating
semicolon (or block ending). The possible modifiers are:
if (EXPR) { }
unless (EXPR) { }
foreach (LIST ) { }
while (EXPR ) { }
until (EXPR ) { }
The EXPR following the modifier is referred to as the "condition". Its truth or falsehood determines
how the modifier will behave.
if executes the statement once if and only if the condition is true .
unless is the opposite, it executes the statement if the condition is false (unless the condition is true).
The foreach modifier is an iterator: it executes the statement once for each item in the LIST (with $_
aliased to each item in turn).
while repeats the statement while the condition is true.
until does the opposite, it repeats the statement until the condition is true (or while the condition is
false): The while and until modifiers have the usual "while loop" semantics (conditional
evaluated first).
Page 42VI, October 2006
Perl statement modifiers
if / if else / if elsif else
#!/usr/bin/perl
use strict;
use warnings;
print "\nEnter your name (then press \"return\" when done):\t";
#get information from the terminal window
my $name = <STDIN>;
#remove trailing "\n" if any
chomp $name;
if ($name eq "Couchepin") { print "Hello Mr President !\n" ; }
exit ;
Page 43VI, October 2006
Perl statement modifiers
if / if else / if elsif else
#!/usr/bin/perl
use strict;
use warnings;
print "\nEnter your name (then press \"return\" when done):\t";
#get information from the terminal window
my $name = <STDIN>;
#remove trailing "\n" if any
chomp $name;
if ($name eq "Couchepin") { print "Hello Mr President !\n" ; }
else { print "Hello $name !\n" ; }
exit ;
Page 44VI, October 2006
Perl statement modifiers
if / if else / if elsif else
#!/usr/bin/perl
use strict;
use warnings;
print "\nEnter your name (then press \"return\" when done):\t";
#get information from the terminal window
my $name = <STDIN>;
#remove trailing "\n" if any
chomp $name;
if ($name eq "Couchepin") { print "Hello Mr President !\n" ; }
elsif ($name eq "Falquet") { print "Good day to you Master $name !\n" ; }
else { print "Hello $name !\n" ; }
exit ;
Page 45VI, October 2006
Perl statement modifiers
Perl looping the for/foreach loop:
"Passing an array":foreach my $element ( @array ) {
# do something with the element
}
"Passing a hash":foreach my $key (keys %hash) {
print "The value of $key is $hash{$key}\n";
}
"specify 3 EXPR inside the (): initial state, condition and loop expression":
for ($i = 0; $i <= 10; $i=$i+1 ) {
#execute the contents of the block as long as $i is less than, or equal to 10 or while $i is smaller than 10.
}
Page 46VI, October 2006
Perl statement modifiers
Perl looping the for/foreach loop:
#!/usr/bin/perl
use strict;
use warnings;
my $counter;
for ($counter=1;$counter<=10;$counter++) {
print "I can count up to $counter !\n";
}
exit ;
I can count up to 1 !
I can count up to 2 !
I can count up to 3 !
I can count up to 4 !
I can count up to 5 !
I can count up to 6 !
I can count up to 7 !
I can count up to 8 !
I can count up to 9 !
I can count up to 10 !
Page 47VI, October 2006
Perl statement modifiers
Perl looping the for/foreach loop:
#!/usr/bin/perl
use strict;
use warnings;
my @names = (
"Simon","Arnaud","Todd","Natacha",
"Francesca","Jan","Jeremy","Claudia",
"Magdalena","Marcel","James","Joachim",
"Sutada","Mingkwan","sivaraman","Ralf",
"Kurt","Liviu","Dinesh","Eleonore", "Paul","Fekadu"
);
foreach my $name (@names) {
print "Hello $name !\n";
}
exit ;
vioannid$ ./list_fname.pl
Hello Simon !
Hello Arnaud !
Hello Todd !
Hello Natacha !
Hello Francesca !
Hello Jan !
Hello Jeremy !
Hello Claudia !
Hello Magdalena !
Hello Marcel !
Hello James !
Hello Joachim !
Hello Sutada !
Hello Mingkwan !
Hello sivaraman !
Hello Ralf !
Hello Kurt !
Hello Liviu !
Hello Dinesh !
Hello Eleonore !
Hello Paul !
Hello Fekadu !
vioannid$
Page 48VI, October 2006
Perl statement modifiers
Perl looping the for/foreach loop:
#!/usr/bin/perl
use strict;
use warnings;
my @names = (
"Simon","Arnaud","Todd","Natacha",
"Francesca","Jan","Jeremy","Claudia",
"Magdalena","Marcel","James","Joachim",
"Sutada","Mingkwan","sivaraman","Ralf",
"Kurt","Liviu","Dinesh","Eleonore", "Paul","Fekadu"
);
foreach (sort @names) {
print "Hello $_ !\n";
}
exit ;
vioannid$ ./list_fname.pl
Hello Arnaud !
Hello Claudia !
Hello Dinesh !
Hello Eleonore !
Hello Fekadu !
Hello Francesca !
Hello James !
Hello Jan !
Hello Jeremy !
Hello Joachim !
Hello Kurt !
Hello Liviu !
Hello Magdalena !
Hello Marcel !
Hello Mingkwan !
Hello Natacha !
Hello Paul !
Hello Ralf !
Hello Simon !
Hello Sutada !
Hello Todd !
Hello sivaraman !
vioannid$
Page 49VI, October 2006
Perl special variables (small extract)
$_ The default input and pattern searching space.
$& The string matched by the last successful pattern match.
$` The string preceding whatever was matched by the last successful pattern match.
$' The string following whatever was matched by the last successful pattern match.
$! If a system or library call fails, it sets this variable This means that the value of $! is
meaningful only immediately after a failure.
$/ The input record separator, newline by default .
$$ The process number of the Perl running this script.
@ARGV commandline arguments (space separation by default).
note:
$ARGV[0] first commandline argument …
Page 50VI, October 2006
Perl statement modifiers
Perl looping the for/foreach loop:
#!/usr/bin/perl
use strict; use warnings;
my %names = (
"Barkow"=>"Simon", "Basle"=>"Arnaud",
"Blevins"=>"Todd", "Bodenhausen"=>"Natacha",
"Botta"=>"Francesca", "Kerschgens"=>"Jan",
"Keusch"=>"Jeremy", "Kutter"=>"Claudia",
"Livingstone"=>"Magdalena", "Meury"=>"Marcel",
"Moore"=>"James", "Muller"=>"Joachim",
"Mungpakdee"=>"Sutada",
"Nipitwattanaphon"=>"Mingkwan",
"Padavattan"=>"sivaraman", "Paul"=>"Ralf",
"Tobler"=>"Kurt", "Vanoaica"=>"Liviu", "Vellore
Palanivelu"=>"Dinesh", "Wassmann"=>"Paul",
"Yadetie"=>"Fekadu", "von Castelmur"=>"Eleonore",
);
foreach my $key (sort keys %names) {
print "The firstname of $key is $names{$key}\n";
}
exit ;
vioannid$ ./list_fname_hash.pl
The firstname of Barkow is Simon
The firstname of Basle is Arnaud
The firstname of Blevins is Todd
The firstname of Bodenhausen is Natacha
The firstname of Botta is Francesca
The firstname of Kerschgens is Jan
The firstname of Keusch is Jeremy
The firstname of Kutter is Claudia
The firstname of Livingstone is Magdalena
The firstname of Meury is Marcel
The firstname of Moore is James
The firstname of Muller is Joachim
The firstname of Mungpakdee is Sutada
The firstname of Nipitwattanaphon is Mingkwan
The firstname of Padavattan is sivaraman
The firstname of Paul is Ralf
The firstname of Tobler is Kurt
The firstname of Vanoaica is Liviu
The firstname of Vellore Palanivelu is Dinesh
The firstname of Wassmann is Paul
The firstname of Yadetie is Fekadu
The firstname of von Castelmur is Eleonore
vioannid$
Page 51VI, October 2006
Perl statement modifiers
Perl looping the while loop
while ( condition ) {
#execute the contents of the block
}
Warning: Infinite Loop !!!
while (1) {
#execute the contents of the block forever !
}
True/False
In Perl some variables are considered true:
- integer with a nonzero value
- string with nonzero length
- array with at least one element
- hash with at least one key/value pair
For example:
$lang = "Perl"; # < true
$version = 5.6; # < true
$zero = 0; # < false
$empty = ""; # < false
@states = (); # < false
%table = (1 => "one"); # < true
Page 52VI, October 2006
#!/usr/bin/perl
use strict;
use warnings;
my $number = 1;
while ($number<=10) {
print "I can count up to $number !";
$number+=1; #Ha !
}
exit ;
Perl statement modifiers
Perl looping the while loop
#!/usr/bin/perl
use strict;
use warnings;
my $number = 1;
while ($number<=10) {
print "I can count up to $number !";
}
exit ; #really ? Tip:
To stop a "looping" script press CTRL+C …
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
I can count up to 1 !
^C
vioannid$
Page 53VI, October 2006
#!/usr/bin/perl
use strict;
use warnings;
my $number = 1;
while ($number<=10) {
print "I can count up to $number !";
$number+=1; #Ha !
}
exit ;
Perl statement modifiers
Perl looping the while loop
#!/usr/bin/perl
use strict;
use warnings;
my $number = 1;
while ($number<=10) {
print "I can count up to $number !";
$number = $number+1;
#same as $number += 1;
#same as $number++;
}
exit ;
vioannid$ ./list_while_array.pl
I can count up to 1 !
I can count up to 2 !
I can count up to 3 !
I can count up to 4 !
I can count up to 5 !
I can count up to 6 !
I can count up to 7 !
I can count up to 8 !
I can count up to 9 !
I can count up to 10 !
vioannid$
Page 54VI, October 2006
Perl Documents, help, debugging
perl -h
perldoc <keyword>
Web help
www.perl.org
www.perl.com
Books
O’Reilly
www.oreilly.com
Debugging?
use strict;
use warnings;
"abuse" of the print !
./script.pl -d
(debug mode)
man perldebug
Page 55VI, October 2006
Perl