Professional Documents
Culture Documents
Introduction To Perl: By: Cédric Notredame (Adapted From BT Mcinnes)
Introduction To Perl: By: Cédric Notredame (Adapted From BT Mcinnes)
Part I
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
3
Resources For Perl
Books:
Learning Perl
By Larry Wall
Published by O'Reilly
Programming Perl
By Larry Wall,Tom Christiansen and Jon Orwant
Published by O'Reilly
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
The Basic Hello World Program
which perl
pico hello.pl
Program:
#! /…path…/perl -w
print “Hello World!\n”;
6
“Hello World” Observations
“.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
Variables and Their Content
Numerical Literals
Numerical Literals
6 Integer
12.6 Floating Point
1e10 Scientific Notation
6.4E-33 Scientific Notation
4_348_348 Underscores instead of
commas for long numbers
9
String Literals
String Literals
“There is more than one way to do it!”
'Just don't create a file called -rf.'
“Beauty?\nWhat's that?\n”
“”
“Real programmers can write assembly in any
language.”
11
Operators on Scalar Variables
Numeric and Logic Operators
Typical : +, -, *, /, %, ++, --, +=, -=, *=, /=, ||, &&, ! ect
…
Not typical: ** for exponentiation
String Operators
Concatenation: “.” - similar to strcat
$first_name = “Larry”;
$last_name = “Wall”;
$full_name = $first_name . “ “ . $last_name;
12
Equality Operators for Strings
Equality/ Inequality : eq and ne
$language = “Perl”;
if ($language == “Perl”) ... # Wrong!
if ($language eq “Perl”) ... #Correct
13
Relational Operators for Strings
Greater than
Numeric : > String : gt
Greater than or equal to
Numeric : >= String : ge
Less than
Numeric : < String : lt
Less than or equal to
Numeric : <= String : le
14
String Functions
Convert to upper case
$name = uc($name);
Convert only the first char to upper case
$name = ucfirst($name);
15
A String Example Program
Convert to upper case
$name = uc($name);
Convert only the first char to upper case
$name = ucfirst($name);
16
A String Example Program
#!/usr/local/bin/perl
$var1 = “larry”;
$var2 = “moe”;
$var3 = “shemp”;
17
Variable Interpolation
Common Example :
19
Numbers 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!
20
Control Structures: Loops and Conditions
If ... else ... statements
if ( $weather eq “Rain” )
{
print “Umbrella!\n”;
}
elsif ( $weather eq “Sun” ) {
print “Sunglasses!\n”;
}
else {
print “Anti Radiation Armor!\n”;
}
22
Unless ... else Statements
Unless Statements are the opposite of if ... else
statements.
24
Until Loop
The until function evaluates an expression
repeatedly until a specific condition is met.
Example:
$i = 0;
until ($i == 1000) {
print “$i\n”;
$i++;
}
25
For Loops
Syntax 1:
for ( $i = 0; $i <= 1000; $i=$i+2 )
{
print “$i\n”;
}
Syntax 2:
for $i(0..1000)
{
print “$i\n”;
}
26
Moving around in a Loop
next: ignore the current iteration
last: terminates the loop.
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
…..
30
Exercise: 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:
Patient 1 99
Patient 2 65
Patient 3 89
….
Tip:
- use the srand to seed the random number
generator
-use rand 100 to generate values between 0 and
100 :
rand 100 31
Exercise
Question:
35
Arrays cont ...
37
Numerical Sorting Example
#!/usr/local/bin/perl -w
@unsortedArray = (3, 10, 76, 23, 1, 54);
@sortedArray = sort numeric @unsortedArray;
sub numeric
{
return $a <=> $b;
}
# Numbers: $a <=> $b : -1 if $a<$b , 0 if $a== $b, 1 if $a>$b
# Strings: $a cpm $b : -1 if $a<$b , 0 if $a== $b, 1 if $a>$b
38
String Sorting Example
#!/usr/local/bin/perl -w
@unsortedArray = (“Larry”, “Curly”, “moe”);
@sortedArray = sort { lc($a) cmp lc($b)} @unsortedArray;
39
Foreach
Foreach allows you to iterate over an array
Example:
foreach $element (@array)
{
print “$element\n”;
}
This is similar to :
for ($i = 0; $i <= $#array; $i++)
{
print “$array[$i]\n”;
}
40
Sorting 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 ”;
}
Syntax
@index=(0,1,2,3,4);
@name=(“V”,“W”,”X”,”Y”,”Z”);
@age=(10,20, 15, 20, 10);
@income=(100,670, 280,800,400);
Output:
Name X Age A Income I
…
Tip:
42
-Sort the index, using information contained in the other arrays.
Exercise: Sorting According to
Multiple Criterion
@index=(0,1,2,3,4,5);
@name=(“V”,“W”,”X”,”Y”,”Z”);
@age=(10,20, 15, 20, 10);
@income=(100,670, 280,800,400);
45
Split cont..
Split on any character
@array = split( /:/, “10:20:30:40”);
# array has 4 elements : 10, 20, 30, 40
46
Arrays to Strings
Array to space separated string
@array = (“Larry”, “Curly”, “Moe”);
$string = join( “;“, @array);
# string = “Larry;Curly;Moe”
47
Joining Arrays cont…
Join with any character you want
@array = ( “10”, “20”, “30”, “40” );
$string = join( “:”, @array);
# string = “10:20:30:40”
48
Arrays as Stacks and Lists
To append to the end of an array :
@array = ( “Larry”, “Curly”, “Moe” );
push (@array, “Shemp” );
print $array[3]; # prints “Shemp”
49
Arrays as Stacks and Lists
Into
“five couples were administered the enquiry 1”
….
51
Exercise: Spliting
Use split, shift and push to turn the following string:
52
Multidimentional Arrays
Multi Dimensional Arrays
Better use Hash tables (cf later)
If you need to:
@tab=([‘Monday’,’Tuesday’],
[‘Morning’,’Afternoon’,’Evening’]);
$a=$tab[0][0] # $a == ‘Monday’
$tab2=(‘midnight’, ‘Twelve’);
$tab[2]=\@tab2 # integrate tab2 as the last row
of tab
54
Thank you