Practical Extraction and Report Language

« is a language of getting your job done »

« There is more than one way to do it »

Larry Wall

VI, October 2006 Page 1

Perl

Outline :

History

Structure of a simple Perl script

Perl variables scalar ($) array (@) hash (%)

Operators (numeric, string & logical)

Statement modifiers (if/elsif/else, for/foreach, while)

VI, October 2006 Page 2 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 "

VI, October 2006 Page 3

Perl history

A few dates:

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).

VI, October 2006 Page 4 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.

VI, October 2006 Page 5

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 integration interface (DBI) supports thirdparty 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).

VI, October 2006 Page 6 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.

VI, October 2006 Page 7

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 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:

pcX: vioannid$ which perl pcY: vioannid$ which perl /usr/bin/perl /usr/local/bin/perl

VI, October 2006 Page 8 Perl Hello world !

My first program (hello.pl) :

#!/usr/local/bin/perl perl script use strict; use warnings;

#tell the program to print "Hello world" print "Hello world" ;

#tell the program to exit exit ; #!/import/bc2/soft/bin/perl5/perl

[embnet01@bc2-linux3 ~]$ which perl /import/bc2/soft/bin/perl5/perl UNIX shell

computerX: vioannid$ which perl computerY: vioannid$ which perl /usr/bin/perl /usr/local/bin/perl

VI, October 2006 Page 9

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 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) VI, October 2006 Page 10 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…

VI, October 2006 Page 11

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.

VI, October 2006 Page 12 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)

VI, October 2006 Page 13

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.

VI, October 2006 Page 14 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 ; output: Do not forget to make the file executable: vioannid$ chmod a+x hello.pl

vioannid$ ./hello.pl Hello worldvioannid$

VI, October 2006 Page 15

Perl Hello world !!

Print :

#!/usr/local/bin/perl vioannid$ ./hello2.pl Hello use strict; world use warnings; Hello world Helloworld #play with the print statement vioannid$

#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"; Important: #tell the program to exit Unix & all Unix flavors: \n exit ; Mac OS : \r Windows: \r\n

VI, October 2006 Page 16 Perl variables and data types

Variables are containers which can hold data of a various 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

VI, October 2006 Page 17

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

VI, October 2006 Page 18 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

VI, October 2006 Page 19

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…

VI, October 2006 Page 20 Perl variables - Scalars

Important strings functions I

#!/usr/bin/perl use strict; use warnings;

my $pet_string = "This is to TEST\nsome string functions"; This is to TEST print $pet_string; some string functions # lc returns lowercased version of $pet_string my $lc_string = lc($pet_string); print $lc_string; this is to test some string functions # uc returns uppercased version of $pet_string my $uc_string = uc($pet_string); print $uc_string; THIS IS TO TEST SOME STRING FUNCTIONS # length returns the length of $pet_string my $length_string = length($pet_string); print "$length_string"; 38

print "*"x10; print "\t".("*"x10)."\n"; ********** **********

exit;

VI, October 2006 Page 21

Perl variables - Scalars

Important strings functions II #!/usr/bin/perl TEST of some my $pet_string = "TEST of some\nstring functions\n"; string functions print $pet_string;

# reverses $pet_string (character by character) my $rev_string = reverse($pet_string); snoitcnuf gnirts print $rev_string."\n"; emos fo TSET # takes 3 arguments: string value, zero-based # initial position and length for the substring TEST of some my $sub_string = substr ($pet_string,0,15); print $sub_string."\n"; TEST of some # if a string ends in a newline character, chomp removes it string functions my $chomp_string = $pet_string; TEST of some print $chomp_string; chomp($chomp_string); string functions print $chomp_string; TEST of some # chop removes the last character of a string string functionsTEST of some my $chop_string = $chomp_string; string functionsTEST of some print $chop_string; chop($chop_string); print $chop_string; string functionvioannid$ exit;

VI, October 2006 Page 22 Perl variables - Arrays & Hashes

Multivalued Data Structures: Tue Wed Tuesday Wednesday

%days Thu Mon Thursday Monday

Sat @locomotion Fri Saturday

0 1 2 3 Friday car bike van plane Sun Sunday

VI, October 2006 Page 23

Perl variables - Arrays

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. #!/usr/bin/perl

# array of strings my @string_numbers = ('One', 'Two', 'Three', 'Four'); OneTwoThreeFour print @string_numbers; print "\n";

# array of integers my @numeric_numbers = (1..5); 1 2 3 4 5 print "@numeric_numbers\n";

my @numeric_numbers2 = (1,2,3,4,5); 1 2 3 4 5 print "@numeric_numbers2\n"; print "$string_numbers[2]\n"; Three exit;

VI, October 2006 Page 24 Perl variables - Arrays

arrays II

#!/usr/bin/perl

# array of strings my @string_numbers = ('One', 'Two', 'Three', 'Four');

# replaces One with Zero in @string_numbers $string_numbers[0] = 'Zero'; Zero Two Three Four print "@string_numbers\n";

my @sort_string_numbers = sort @string_numbers; Four Three Two Zero print "@sort_string_numbers\n";

print scalar @string_numbers; 4 print "\n";

my $nb = @string_numbers; print "$nb\n"; 4

exit;

VI, October 2006 Page 25

Perl variables - Arrays

arrays III

#!/usr/bin/perl

my @string_numbers = ('Zero', 'Two', 'Three', 'Four'); my $end = $string_numbers[$#string_numbers]; print "$end\n"; Four

# swap values ($gene1, $gene2) = ($gene2, $gene1);

# variable interpolation my @login = ("$username", "$password"); my @anyarray = (6, "hello", @string_numbers ); 6 hello Zero Two Three Four my @rev_anyarray = reverse @rev_anyarray; print "@anyarray\n"; print "@rev_anyarray\n"; Four Three Two Zero hello 6 exit;

VI, October 2006 Page 26 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

VI, October 2006 Page 27

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.

F E D C B A

VI, October 2006 Page 28 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.

F

E D C B A F

VI, October 2006 Page 29

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

F E D C B

A

VI, October 2006 Page 30 Perl variables - Arrays & Hashes

Multivalued Data Structures: Tue Wed Tuesday Wednesday

%days Thu Mon Thursday Monday

Sat @locomotion Fri Saturday

0 1 2 3 Friday car bike van plane Sun Sunday

VI, October 2006 Page 31

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 '%'

Key Value %days TTT Phe Tue TCT Ser Wed Tuesday Wednesday #!/usr/bin/perl TGT Cys TAT Tyr Thu my %codon3 = ( Mon Thursday "TTT" => "Phe", Monday "TTA" => "Leu", Sat ); Fri Saturday Friday print $codon3{'TTT'}; Sun print "\n"; vioannid$ ./hash.pl Sunday Phe exit; vioannid$

VI, October 2006 Page 32 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)

VI, October 2006 Page 33

Perl variables

hashes I

#!/usr/bin/perl my %some_hash = ("John", "Travolta", "Betty", "Bossy"); print $some_hash{"John"}."\n"; Travolta my %capitals = ( 'china' => 'beijing', 'france' => 'paris', 'italy' => 'rome', 'switzerland' => 'bern', ); switzerlandbernitalyromefranceparischinabeijing print %capitals; print "\n"; print $capitals{'china'}."\n"; beijing my @k = keys %capitals; my @v = values %capitals; switzerland italy france china print "@k\n"; print "@v\n"; bern rome paris beijing exit;

VI, October 2006 Page 34 Perl variables

hashes II

#!/usr/bin/perl my %capitals = ( 'china' => 'beijing', 'france' => 'paris', 'italy' => 'rome', 'switzerland' => 'bern', ); my $nb = keys %capitals; 4 print "$nb\n"; my %rev_capitals = reverse %capitals; print %rev_capitals; beijingchinabernswitzerlandparisfranceromeitaly print "\n"; print $rev_capitals{'china'}."\n"; print $rev_capitals{'beijing'}."\n"; china exit;

VI, October 2006 Page 35

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:

Each time we use 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 = ; Please enter your Lastname: Ioannidis

print "Please enter your Firstname: "; my $firstname = ; Please enter your Firstname: Vassilios Hello Vassilios print "Hello $firstname $lastname,\n Ioannidis I hope you like Perl programming !\n"; ,

exit; I hope you like Perl programming !

VI, October 2006 Page 36 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:

Each time we use 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 = ; Please enter your Lastname: Ioannidis chomp $lastname; print "Please enter your Firstname: "; my $firstname = ; Please enter your Firstname: Vassilios chomp $firstname; Hello Vassilios Ioannidis, print "Hello $firstname $lastname,\n I hope you like Perl programming ! I hope you like Perl programming !\n"; exit;

VI, October 2006 Page 37

Perl operators

Perl operators Arithmetic Numeric comparison String comparison + addition == equality eq equality - subtraction != inequality ne inequality * multiplication < less than lt less than / division > greater than gt greater than <= less than or equal le less than or equal >= greater 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).

VI, October 2006 Page 38 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$

VI, October 2006 Page 39

Perl operators

Perl operators

Boolean logic Miscellaneous && and = assignment || or . string concatenation ! not 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";

VI, October 2006 Page 40 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).

VI, October 2006 Page 41

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 = ;

#remove trailing "\n" if any chomp $name; if ($name eq "Couchepin") { print "Hello Mr President !\n" ; } exit ;

VI, October 2006 Page 42 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 = ;

#remove trailing "\n" if any chomp $name; if ($name eq "Couchepin") { print "Hello Mr President !\n" ; } else { print "Hello $name !\n" ; } exit ;

VI, October 2006 Page 43

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 = ;

#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 ;

VI, October 2006 Page 44 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. }

VI, October 2006 Page 45

Perl statement modifiers

Perl looping the for/foreach loop:

#!/usr/bin/perl I can count up to 1 ! use strict; I can count up to 2 ! use warnings; I can count up to 3 ! I can count up to 4 ! my $counter; I can count up to 5 ! I can count up to 6 ! for ($counter=1;$counter<=10;$counter++) { I can count up to 7 ! print "I can count up to $counter !\n"; I can count up to 8 ! } I can count up to 9 ! I can count up to 10 ! exit ;

VI, October 2006 Page 46 Perl statement modifiers

vioannid$ ./list_fname.pl Perl looping the for/foreach loop: Hello Simon ! Hello Arnaud ! Hello Todd ! #!/usr/bin/perl Hello Natacha ! Hello Francesca ! use strict; Hello Jan ! use warnings; Hello Jeremy ! Hello Claudia ! my @names = ( Hello Magdalena ! "Simon","Arnaud","Todd","Natacha", Hello Marcel ! "Francesca","Jan","Jeremy","Claudia", Hello James ! "Magdalena","Marcel","James","Joachim", Hello Joachim ! "Sutada","Mingkwan","sivaraman","Ralf", Hello Sutada ! "Kurt","Liviu","Dinesh","Eleonore", "Paul","Fekadu" Hello Mingkwan ! ); Hello sivaraman ! Hello Ralf ! foreach my $name (@names) { Hello Kurt ! print "Hello $name !\n"; Hello Liviu ! } Hello Dinesh ! Hello Eleonore ! exit ; Hello Paul ! Hello Fekadu ! vioannid$

VI, October 2006 Page 47

Perl statement modifiers

vioannid$ ./list_fname.pl Perl looping the for/foreach loop: Hello Arnaud ! Hello Claudia ! Hello Dinesh ! #!/usr/bin/perl Hello Eleonore ! Hello Fekadu ! use strict; Hello Francesca ! use warnings; Hello James ! Hello Jan ! my @names = ( Hello Jeremy ! "Simon","Arnaud","Todd","Natacha", Hello Joachim ! "Francesca","Jan","Jeremy","Claudia", Hello Kurt ! "Magdalena","Marcel","James","Joachim", Hello Liviu ! "Sutada","Mingkwan","sivaraman","Ralf", Hello Magdalena ! "Kurt","Liviu","Dinesh","Eleonore", "Paul","Fekadu" Hello Marcel ! ); Hello Mingkwan ! Hello Natacha ! foreach (sort @names) { Hello Paul ! print "Hello $_ !\n"; Hello Ralf ! } Hello Simon ! Hello Sutada ! exit ; Hello Todd ! Hello sivaraman ! vioannid$

VI, October 2006 Page 48 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 …

VI, October 2006 Page 49

Perl statement modifiers

Perl looping the for/foreach loop:

#!/usr/bin/perl vioannid$ ./list_fname_hash.pl The firstname of Barkow is Simon use strict; use warnings; The firstname of Basle is Arnaud The firstname of Blevins is Todd my %names = ( The firstname of Bodenhausen is Natacha "Barkow"=>"Simon", "Basle"=>"Arnaud", The firstname of Botta is Francesca "Blevins"=>"Todd", "Bodenhausen"=>"Natacha", The firstname of Kerschgens is Jan "Botta"=>"Francesca", "Kerschgens"=>"Jan", The firstname of Keusch is Jeremy "Keusch"=>"Jeremy", "Kutter"=>"Claudia", The firstname of Kutter is Claudia "Livingstone"=>"Magdalena", "Meury"=>"Marcel", The firstname of Livingstone is Magdalena "Moore"=>"James", "Muller"=>"Joachim", The firstname of Meury is Marcel "Mungpakdee"=>"Sutada", The firstname of Moore is James "Nipitwattanaphon"=>"Mingkwan", The firstname of Muller is Joachim "Padavattan"=>"sivaraman", "Paul"=>"Ralf", The firstname of Mungpakdee is Sutada "Tobler"=>"Kurt", "Vanoaica"=>"Liviu", "Vellore The firstname of Nipitwattanaphon is Mingkwan Palanivelu"=>"Dinesh", "Wassmann"=>"Paul", The firstname of Padavattan is sivaraman "Yadetie"=>"Fekadu", "von Castelmur"=>"Eleonore", The firstname of Paul is Ralf ); The firstname of Tobler is Kurt The firstname of Vanoaica is Liviu foreach my $key (sort keys %names) { The firstname of Vellore Palanivelu is Dinesh print "The firstname of $key is $names{$key}\n"; The firstname of Wassmann is Paul } The firstname of Yadetie is Fekadu The firstname of von Castelmur is Eleonore exit ; vioannid$

VI, October 2006 Page 50 Perl statement modifiers

Perl looping the while loop 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 while ( condition ) { #execute the contents of the block For example: } $lang = "Perl"; # < true

$version = 5.6; # < true

Warning: Infinite Loop !!! $zero = 0; # < false while (1) { $empty = ""; # < false #execute the contents of the block forever ! } @states = (); # < false %table = (1 => "one"); # < true

VI, October 2006 Page 51

Perl statement modifiers

Perl looping the while loop 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 ! #!/usr/bin/perl I can count up to 1 ! I can count up to 1 ! use strict; I can count up to 1 ! use warnings; I can count up to 1 ! I can count up to 1 ! my $number = 1; I can count up to 1 ! I can count up to 1 ! while ($number<=10) { I can count up to 1 ! print "I can count up to $number !"; I can count up to 1 ! print "$In cuamnb ceoru+n=t1 u;p to $numb#Hera ! "! ; I can count up to 1 ! } I can count up to 1 ! ^C e}xit ; vioannid$ exit ; #really ? Tip:

To stop a "looping" script press CTRL+C …

VI, October 2006 Page 52 Perl statement modifiers

Perl looping the while loop 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 ! #!/usr/bin/perl I can count up to 5 ! I can count up to 6 ! use strict; I can count up to 7 ! use warnings; I can count up to 8 ! I can count up to 9 ! my $number = 1; I can count up to 10 ! vioannid$ while ($number<=10) { print "I can count up to $number !"; print "$In cuamnb ceoru+n=t1 u;p to $numb#Hera ! "! ; } $number = $number+1; #same as $number += 1; e x i t ; #same as $number++; } exit ;

VI, October 2006 Page 53

Perl Documents, help, debugging

perl -h Debugging?

perldoc use strict; use warnings; Web help www.perl.org www.perl.com "abuse" of the print !

Books O’Reilly ./script.pl -d www.oreilly.com (debug mode) man perldebug

VI, October 2006 Page 54 Perl

VI, October 2006 Page 55