Introduction to Perl Part I

By: Cédric Notredame (Adapted from BT McInnes)

What is Perl? 
Perl is a Portable Scripting Language  No compiling is needed.  Runs on Windows, UNIX, LINUX and cygwin  Fast and easy text processing capability  Fast and easy file handling capability  Written by Larry Wall  ³Perl is the language for getting your job done.´  Too Slow For Number Crunching  Ideal for Prototyping
2

How to Access Perl 
To install at home  Perl Comes by Default on Linux, Cygwin, MacOSX  www.perl.com Has rpm's for Linux  www.activestate.com Has binaries for Windows  Latest Version is 5.8  To check if Perl is working and the version number  % perl -v

3

Resources For Perl 
Books: 

Learning Perl 


By Larry Wall Published by O'Reilly By Larry Wall,Tom Christiansen and Jon Orwant Published by O'Reilly 

Programming Perl 
 

Web Site 

http://safari.oreilly.com 

Contains both Learning Perl and Programming Perl in ebook form

4

Web Sources for Perl 
Web 
  

www.perl.com www.perldoc.com www.perl.org www.perlmonks.org

5

 Save this as ³hello.pl  Program: #! /«path«/perl -w print ³Hello World!\n´.The Basic Hello World Program  which perl  pico hello.pl ./hello.pl 6  Run it as follows:  .pl´  Give it executable permissions  chmod a+x hello.

pl´ extension is optional but is commonly used  The first line ³#!/usr/local/bin/perl´ tells UNIX where to find Perl  ³-w´ switches on warning : not required but a really good idea 7 .³Hello World´ Observations  ³.

Variables and Their Content .

4E-33 4_348_348 Integer Floating Point Scientific Notation Scientific Notation Underscores instead of commas for long numbers 9 .Numerical Literals  Numerical Literals      6 12.6 1e10 6.

´  Quotes from Larry Wall 10 .' ³Beauty?\nWhat's that?\n´ ³´ ³Real programmers can write assembly in any language.String Literals  String Literals      ³There is more than one way to do it!´ 'Just don't create a file called -rf.

# now an integer  $a = ³perl´.Types of Variables  Types of variables:  Scalar variables : $a.. # now a string 11 . STDERR  Variables do not need to be declared  Variable type (int. $b. char. $c  Array variables : @array  Hash variables : %hash  File handles : STDIN.) is decided at run time  $a = 5. STDOUT.. .

/.´ .similar to strcat $first_name = ³Larry´. ||. %. *=. ++. +=. ³ ³ . /=. ! ect «  Not typical: ** for exponentiation  String Operators  Concatenation: ³.Operators on Scalar Variables  Numeric and Logic Operators  Typical : +. $last_name = ³Wall´. &&. *. $full_name = $first_name . --. -. $last_name. 12 . -=.

. if ($language == ³Perl´) . #Correct  Use eq / ne rather than == / != for strings 13 .Equality Operators for Strings  Equality/ Inequality : eq and ne $language = ³Perl´.... # Wrong! if ($language eq ³Perl´) .

Relational Operators for Strings  Greater than  Numeric : > Numeric : >= Numeric : < Numeric : <= String : gt String : ge String : lt String : le  Greater than or equal to   Less than   Less than or equal to  14 .

$name = lcfirst($name).String Functions  Convert to upper case  $name = uc($name). 15  Convert only the first char to lower case  .  Convert only the first char to upper case   Convert to lower case  $name = lc($name). $name = ucfirst($name).

 #!/usr/bin/perl $var1 = ³larry´. sHEMP 16 .A String Example Program  Convert to upper case $name = uc($name). «« Output: Larry.  Convert only the first char to lower case  $name = lcfirst($name). $var3 = ³shemp´.  Convert only the first char to upper case  $name = ucfirst($name). $var2 = ³moe´.   Convert to lower case $name = lc($name). MOE.

$var3 = ³shemp´. print lcfirst(uc($var3)).A String Example Program #!/usr/local/bin/perl $var1 = ³larry´. # Prints 'Larry' # Prints 'MOE' # Prints 'sHEMP' 17 . print uc($var2). $var2 = ³moe´. print ucfirst($var1).

\n´.\n 18 .Variable Interpolation  Perl looks for variables inside strings and replaces them with their value $stooge = ³Larry´ print ³$stooge is one of the three stooges. Produces the output: Larry is one of the three stooges.  This does not happen when you use single quotes print '$stooge is one of the three stooges. Produces the output: $stooge is one of the three stooges.\n¶.

Character Interpolation  List of character escapes that are recognized when using double quoted strings    \n \t \r newline tab carriage return  Common Example :  print ³Hello\n´. # prints Hello and then a return 19 .

print $a + 18. it will use it as a number $a = 4. but .. # will print 40! 20 ..Numbers and Strings are Interchangeable  If a scalar variable looks like a number and Perl needs a number. # print $b ± 10. # $b = ³50´. # a number prints 22 looks like a string.

Control Structures: Loops and Conditions .

If ... statements if ( $weather eq ³Rain´ ) { print ³Umbrella!\n´. else . } elsif ( $weather eq ³Sun´ ) { print ³Sunglasses!\n´. } else { print ³Anti Radiation Armor!\n´. } 22 ...

else statements.. else Statements  Unless Statements are the opposite of if . unless ($weather eq ³Rain´) { print ³Dress as you wish!\n´.. } else { print ³Umbrella!\n´.. }  And again remember the braces are required! 23 .Unless ..

} 24 .While Loop  Example : $i = 0. $i++. while ( $i <= 1000 ) { print ³$i\n´.

$i++.Until Loop  The until function evaluates an expression repeatedly until a specific condition is met.  Example: $i = 0. } 25 . until ($i == 1000) { print ³$i\n´.

$i=$i+2 ) { print ³$i\n´. } 26  . } Syntax 2:  for $i(0.For Loops  Syntax 1:  for ( $i = 0.1000) { print ³$i\n´.. $i <= 1000.

} } 27 . } else {print ³$i\n´. } elsif($i == 5) { last. $i < 10. $i++) { if ($i == 1 || $i == 3) { next.Moving around in a Loop  next: ignore the current iteration  last: terminates the loop.  What is the output for the following code snippet: for ( $i = 0.

Answer 0 2 4 .

Exercise  Use a loop structure and code a program that produces the following output: A AA AAA AAAB AAABA AAABAA AAABAAA AAABAAAB «. ³A´.. 29 . TIP: $chain = $chain .

$j=0.} print ³$chain\n´. $i<100. $i++) { if ( $j==3){$chain. } 30 .Exercise #! /usr/bin/perl for ($i=0.=³A´.=³B´.} else {$chain. $j++.$j=0.

Tip: . You want to generate an artificial random study for 100 patients: Patient 1 99 Patient 2 65 Patient 3 89 «.Exercise: Generating a Random Sample  A study yields an outcome between 0 and 100 for every patient.use the srand to seed the random number generator -use rand 100 to generate values between 0 and 100 : rand 100 31 .

strings #%d : integer #%f : floating points } 32 . #print ³Patient $i $v\n´.2f\n\n´. printf ³Patient %d %. $v. #%s : chaines.Exercise for ($i=0. $i<100. $i++) { $v=rand 100. $i.

Collections Of Variables: Arrays .

# prints : Larry Curly Moe  Notice that you do not need to loop through the whole array to print it ± Perl does this for you 34 .  To access the whole array.Arrays  Array variable is denoted by the @ symbol  @array = ( ³Larry´. ³Curly´. ³Moe´ ). use the whole array  print @array.

# prints : Larry  Question:  What happens if we access $array[3] ?   Answer1 : Value is set to 0 in Perl Answer2: Anything in C!!!!! 35 .Arrays cont«  Array Indexes start at 0 !!!!!  To access one element of the array : use $  Why? Because every element in the array is scalar  print ³$array[0]\n´.

 $array_size now has 3 in the above example because there are 3 elements in the array 36 .  To find the index of the last element in the array print $#array.. # prints 2 in the previous # example  Note another way to find the number of elements in the array: $array_size = @array..Arrays cont .

Sorting Arrays  Perl has a built in sort function  Two ways to sort:  Default : sorts in a standard string comparisons order  sort LIST  Usersub: create your own subroutine that returns an integer less than. equal to or greater than 0  Sort USERSUB LIST  The <=> and cmp operators make creating sorting subroutines very easy 37 .

76. 0 if $a== $b. 54). 1 if $a>$b 38 . @sortedArray = sort numeric @unsortedArray. 1 if $a>$b -1 if $a<$b . # prints 3 10 76 23 1 54 print ³@sortedArray\n´. 0 if $a== $b. 23. 10. 1. print ³@unsortedArray\n´.Numerical Sorting Example #!/usr/local/bin/perl -w @unsortedArray = (3. } # Numbers: $a <=> $b : # Strings: $a cpm $b : -1 if $a<$b . # prints 1 3 10 23 54 76 sub numeric { return $a <=> $b.

moe ). @sortedArray = sort { lc($a) cmp lc($b)} @unsortedArray. # prints Curly Larry moe 39 .String Sorting Example #!/usr/local/bin/perl -w @unsortedArray = ( Larry . print @unsortedArray\n . Curly . # prints Larry Curly moe print @sortedArray\n .

Foreach  Foreach allows you to iterate over an array  Example: foreach $element (@array) { print ³$element\n´. $i <= $#array. } 40 . }  This is similar to : for ($i = 0. $i++) { print ³$array[$i]\n´.

Sorting with Foreach  The sort function sorts the array and returns the list in sorted order. foreach $element (sort @array) { print ³$element ´. ³Curly´. ³Moe´). }  Prints the elements in sorted order: Curly Larry Moe 41 .  Example : @array( ³Larry´.

@age=(10. } Data  @index=(0.2. 15. 10).´Z´). 42 .´Y´. 20.3.  Output: Name X Age A Income I « Tip: -Sort the index.800.670.400).20. sub numeric { return $a <=> $b. @income=(100.Exercise: Sorting According to Multiple Criterion  Use the following initialization to sort individuals by age and then by income: Syntax @sortedArray = sort numeric @unsortedArray. 280.³W´. @name=(³V´.1.´X´.4). using information contained in the other arrays.

15.´X´.´Y´.800.³W´.20. } } 43 . @income=(100.5).4. 10). 20. foreach $i ( sort my_numeric @index) { print ³$name[$i] $age[$i] $income[$i].Exercise: Sorting According to Multiple Criterion  @index=(0.2.670. @age=(10.3.1. @name=(³V´. } sub my_numeric { if ($age[$a] == $age[$b]) {return $income[$a]<=>$income[$b]. 280. } else {return $age[$a]<=>$age[$b].400).´Z´).

Manipulating Arrays .

Strings to Arrays : split  Split a string into words and put into an array @array = split( /. # array @stooge has 5 elements: c. u. # creates the same array as we saw previously  Split into characters @stooge = split( //. ³curly´ ).Moe´ ). ³Moe´). r.Curly. l./. ³Curly´. @array= (³Larry´. ³Larry. y 45 .

20. # array has 4 elements : 10.Split cont. 40  Split on Multiple White Space @array = split(/\s+/. ³this is a test´. test  More on µ\s+¶ later 46 .  Split on any character @array = split( /:/. is. ³10:20:30:40´). # array has 4 elements : this.. 30. a.

Arrays to Strings  Array to space separated string @array = (³Larry´. # string = ³curly´ 47 . ³y´). @array). ³Moe´). ³r´. $string = join( ³. ³u´. # string = ³Larry. ³Curly´. @stooge ).Moe´  Array of characters to string @stooge = (³c´.³.Curly. $string = join( ³´. ³l´.

$string = join( ³:´. ³30´. @array). ³30´. ³20´. ³40´).Joining Arrays cont«  Join with any character you want @array = ( ³10´. ³20´. $string = join(³->´. # string = ³10:20:30:40´  Join with multiple characters @array = ³10´. @array). ³40´ ). # string = ³10->20->30->40´ 48 .

³Shemp´ ). print $array[3]. ³Curly´.Arrays as Stacks and Lists  To append to the end of an array : @array = ( ³Larry´. ³Moe´ ). # prints ³Shemp´  @array now has the original elements (³Larry´. ³Curly´. ³Moe´) 49 . push (@array. # prints ³Shemp´  To remove the last element of the array (LIFO) $elment = pop @array. print $element.

³Curly´. print $array[3]. ³Curly´. # prints ³Shemp´  The array now contains only :  ³Larry´. unshift @array. # prints ³Shemp´  To remove the first element of the array $element = shift @array.Arrays as Stacks and Lists  To prepend to the beginning of an array @array = ( ³Larry´. ³Shemp´. ³Moe´ ). print $element. # prints ³Moe´ print ³$array[0]. ³Moe´ 50 .

Exercise: Spliting  Instructions  Remove  shift: beginning. shift and push to turn the following string: ³The enquiry 1 was administered to five couples´ ³The enquiry 2 was administered to six couples´ ³The enquiry 3 was administered to eigh couples´ Into ³five couples were administered the enquiry 1´ «. 51 . pop: end Unshift: beginning. push: end  Add   Use split.

$s[1]= ³The enquiry 2 was administered to six couples´. $s).Exercise: Spliting  Use split. $s[2]= ³The enquiry 3 was administered to eigh couples´. foreach $s(@s) { @s2=split (/was administered to/. shift and push to turn the following string: $s[0]= ³The enquiry 1 was administered to five couples´. $new_s=³$s2[1] were admimistered $s2[0]´. } 52 . print ³$new_s\n´.

Multidimentional Arrays .

¶Tuesday¶]. µTwelve¶). $a=$tab[0][0] # $a == µMonday¶ $tab2=(µmidnight¶.Multi Dimensional Arrays  Better use Hash tables (cf later)  If you need to: @tab=([µMonday¶. $tab[2]=\@tab2 # integrate tab2 as the last row of tab  54 .¶Afternoon¶. [µMorning¶.¶Evening¶]).

Thank you .

Sign up to vote on this title
UsefulNot useful