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
Trang 1Introduction to Perl
programming
By: Cédric Notredame (Adapted from BT McInnes)
Trang 2What 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
Trang 3How 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
Trang 4Resources For Perl
Trang 5Web Sources for Perl
Trang 6The Basic Hello World Program
which perl
pico hello.pl
Program:
#! /…path…/perl -w
print “Hello World!\n”;
Save this as “hello.pl”
Give it executable permissions
chmod a+x hello.pl
Run it as follows:
./hello.pl
Trang 7“Hello World” Observations
“.pl” extension is optional but is commonly
Trang 8Variables and Their Content
Trang 9Numerical Literals
Numerical Literals
12.6 Floating Point
1e10 Scientific Notation
6.4E-33 Scientific Notation
4_348_348 Underscores instead of
commas for long numbers
Trang 10String Literals
String Literals
“There is more than one way to do it!”
'Just don't create a file called -rf.'
Trang 11Types of Variables
Types of variables:
Scalar variables : $a, $b, $c
Array variables : @array
Hash variables : %hash
File handles : STDIN, STDOUT, STDERR
Variables do not need to be declared
Variable type (int, char, ) is decided at run time
$a = 5; # now an integer
Trang 12Operators on Scalar Variables
Numeric and Logic Operators
Typical : +, -, *, /, %, ++, , +=, -=, *=, /=, ||, &&, ! ect
Trang 13Equality Operators for Strings
Equality/ Inequality : eq and ne
$language = “Perl”;
if ($language == “Perl”) # Wrong!
if ($language eq “Perl”) #Correct
Use eq / ne rather than == / != for strings
Trang 14Relational Operators for Strings
Trang 16A String Example Program
Convert to upper case
Trang 17A String Example Program
#!/usr/local/bin/perl
$var1 = “larry”;
$var2 = “moe”;
$var3 = “shemp”;
print ucfirst($var1); # Prints 'Larry'
print uc($var2); # Prints 'MOE'
print lcfirst(uc($var3)); # Prints 'sHEMP'
Trang 18Variable Interpolation
Perl looks for variables inside strings and
replaces them with their value
$stooge = “Larry”
print “$stooge is one of the three stooges.\n”;
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.\n’;
Produces the output:
$stooge is one of the three stooges.\n
Trang 19Character Interpolation
List of character escapes that are recognized when
using double quoted strings
Trang 20Numbers and Strings are
Interchangeable
If a scalar variable looks like a number and Perl
needs a number, it will use it as a number
$a = 4; # a number
print $a + 18; # prints 22
$b = “50”; # looks like a string, but
print $b – 10; # will print 40!
Trang 21Control Structures: Loops and Conditions
Trang 23Unless else Statements
Unless Statements are the opposite of if else
statements
unless ($weather eq “Rain”) {
print “Dress as you wish!\n”;
}
else {
print “Umbrella!\n”;
}
Trang 27Moving around in a Loop
next: ignore the current iteration
last: terminates the loop.
What is the output for the following code
Trang 280 2 4
Trang 29 Use a loop structure and code a program that
produces the following output:
Trang 31Exercise: Generating a Random
Sample
A study yields an outcome between 0 and 100
for every patient You want to generate an
artificial random study for 100 patients:
Trang 33Collections Of Variables: Arrays
Trang 34 @array = ( “Larry”, “Curly”, “Moe” );
array
print @array; # prints : Larry Curly Moe
Notice that you do not need to loop through the whole array to print it – Perl does this for you
Trang 35Arrays 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”; # prints : Larry
Question:
What happens if we access $array[3] ?
Trang 36elements in the array:
$array_size = @array;
$array_size now has 3 in the above example because there are 3 elements in the array
Trang 37Sorting 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
Trang 38Numerical Sorting Example
#!/usr/local/bin/perl -w
@unsortedArray = (3, 10, 76, 23, 1, 54);
@sortedArray = sort numeric @unsortedArray;
print “@unsortedArray\n”; # prints 3 10 76 23 1 54
print “@sortedArray\n”; # prints 1 3 10 23 54 76
sub numeric
{
return $a <=> $b;
}
Trang 39#!/usr/local/bin/perl -w
@unsortedArray = (“Larry”, “Curly”, “moe”);
@sortedArray = sort { lc($a) cmp lc($b)} @unsortedArray;
print “@unsortedArray\n”; # prints Larry Curly moe
print “@sortedArray\n”; # prints Curly Larry moe
String Sorting Example
Trang 41Sorting with Foreach
The sort function sorts the array and returns the list in sorted order.
Example :
@array( “Larry”, “Curly”, “Moe”);
foreach $element (sort @array)
{ print “$element ”;
}
Trang 42Exercise: Sorting According to
Trang 43Exercise: Sorting According to
{
if ($age[$a] == $age[$b])
{return $income[$a]<=>$income[$b]; } else
Trang 44Manipulating Arrays
Trang 45Strings to Arrays : split
Split a string into words and put into an array
@array = split( /;/, “Larry;Curly;Moe” );
@array= (“Larry”, “Curly”, “Moe”);
# creates the same array as we saw previously
Split into characters
@stooge = split( //, “curly” );
# array @stooge has 5 elements: c, u, r, l, y
Trang 46Split cont
Split on any character
@array = split( /:/, “10:20:30:40”);
# array has 4 elements : 10, 20, 30, 40
Split on Multiple White Space
@array = split(/\s+/, “this is a test”;
# array has 4 elements : this, is, a, test
More on ‘\s+’ later
Trang 47Arrays to Strings
Array to space separated string
@array = (“Larry”, “Curly”, “Moe”);
$string = join( “;“, @array);
# string = “Larry;Curly;Moe”
Array of characters to string
@stooge = (“c”, “u”, “r”, “l”, “y”);
$string = join( “”, @stooge );
# string = “curly”
Trang 48Joining Arrays cont…
Join with any character you want
Trang 49Arrays as Stacks and Lists
To append to the end of an array :
@array = ( “Larry”, “Curly”, “Moe” );
push (@array, “Shemp” );
print $array[3]; # prints “Shemp”
To remove the last element of the array (LIFO)
$elment = pop @array;
print $element; # prints “Shemp”
@array now has the original elements
Trang 50Arrays as Stacks and Lists
@array = ( “Larry”, “Curly”, “Moe” );
unshift @array, “Shemp”;
print $array[3]; # prints “Moe”
print “$array[0]; # prints “Shemp”
$element = shift @array;
print $element; # prints “Shemp”
The array now contains only :
Trang 51 Unshift: beginning, push: end
Use split, 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
Trang 52Exercise: Spliting
Use split, shift and push to turn the following string:
$s[0]= “The enquiry 1 was administered to five couples”;
$s[1]= “The enquiry 2 was administered to six couples”;
$s[2]= “The enquiry 3 was administered to eigh couples”;
foreach $s(@s)
{
@s2=split (/was administered to/, $s);
$new_s=“$s2[1] were admimistered $s2[0]”;
print “$new_s\n”;
}
Trang 53Multidimentional Arrays
Trang 54Multi Dimensional Arrays
Better use Hash tables (cf later)
If you need to:
Trang 55Thank you