Title: Introduction to Perl Part
1Introduction to PerlPart I
- By Cédric Notredame
- (Adapted from BT McInnes)
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
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
4Resources 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
5Web Sources for Perl
- Web
- www.perl.com
- www.perldoc.com
- www.perl.org
- www.perlmonks.org
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 ax hello.pl
- Run it as follows
- ./hello.pl
7Hello 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
8- Variables and Their Content
9Numerical 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
10String 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. - Quotes from Larry Wall
11Types of Variables
- Types of variables
- Scalar variables a, b, c
- Array variables _at_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
- a perl now a string
12Operators 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
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
14Relational Operators for Strings
- Greater than
- Numeric gt String gt
- Greater than or equal to
- Numeric gt String ge
- Less than
- Numeric lt String lt
- Less than or equal to
- Numeric lt String le
15String Functions
- Convert to upper case
- name uc(name)
- Convert only the first char to upper case
- name ucfirst(name)
- Convert to lower case
- name lc(name)
- Convert only the first char to lower case
- name lcfirst(name)
16A String Example Program
- Convert to upper case
- name uc(name)
- Convert only the first char to upper case
- name ucfirst(name)
- Convert to lower case
- name lc(name)
- Convert only the first char to lower case
- name lcfirst(name)
- !/usr/bin/perl
- var1 larry
- var2 moe
- var3 shemp
-
- Output Larry, MOE, sHEMP
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'
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
19Character Interpolation
- List of character escapes that are recognized
when using double quoted strings - \n newline
- \t tab
- \r carriage return
- Common Example
- print Hello\n prints Hello and then a
return
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!
21- Control Structures Loops and Conditions
22If ... else ... statements
- if ( weather eq Rain )
-
- print Umbrella!\n
-
- elsif ( weather eq Sun )
- print Sunglasses!\n
-
- else
- print Anti Radiation Armor!\n
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
-
- And again remember the braces are required!
24While Loop
- Example
- i 0
- while ( i lt 1000 )
- print i\n
- i
25Until Loop
- The until function evaluates an expression
repeatedly until a specific condition is met. - Example
- i 0
- until (i 1000)
- print i\n
- i
26For Loops
- Syntax 1
- for ( i 0 i lt 1000 ii2 )
- print i\n
-
- Syntax 2
- for i(0..1000)
- print i\n
-
27Moving 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 i lt 10 i)
- if (i 1 i 3) next
- elsif(i 5) last
- else
- print i\n
-
28Answer
29Exercise
- Use a loop structure and code a program that
produces the following output - AAAAAAAAAB
- AAABA
- AAABAA
- AAABAAA
- AAABAAAB
- ..
- TIP chain chain . A
30Exercise
- ! /usr/bin/perlfor (i0, j0 ilt100 i)
-
- if ( j3)chain.Bj0
- else chain.A j
- print chain\n
-
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 - 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
32Exercise
- for (i0 ilt100 i)
-
- vrand 100
- print Patient i v\n
- printf Patient d .2f\n\n, i, vs
chaines, stringsd integer - f floating points
-
33- Collections Of Variables Arrays
34Arrays
- Array variable is denoted by the _at_ symbol
- _at_array ( Larry, Curly, Moe )
- To access the whole array, use the whole array
- print _at_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
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 array0\n prints Larry
- Question
-
- What happens if we access array3 ?
- Answer1 Value is set to 0 in Perl
- Answer2 Anything in C!!!!!
36Arrays cont ...
- 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 _at_array
- array_size now has 3 in the above example
because there are 3 elements in the array
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 ltgt and cmp operators make creating sorting
subroutines very easy
38Numerical Sorting Example
- !/usr/local/bin/perl -w
- _at_unsortedArray (3, 10, 76, 23, 1, 54)
- _at_sortedArray sort numeric _at_unsortedArray
- print _at_unsortedArray\n prints 3 10 76 23 1
54 - print _at_sortedArray\n prints 1 3 10 23 54 76
- sub numeric
-
- return a ltgt b
-
-
- Numbers a ltgt b -1 if altb , 0 if a
b, 1 if agtb - Strings a cpm b -1 if altb , 0 if
a b, 1 if agtb
39String Sorting Example
!/usr/local/bin/perl -w _at_unsortedArray
(Larry, Curly, moe) _at_sortedArray sort
lc(a) cmp lc(b) _at_unsortedArray print
_at_unsortedArray\n prints Larry Curly
moe print _at_sortedArray\n prints Curly
Larry moe
40Foreach
- Foreach allows you to iterate over an array
- Example
- foreach element (_at_array)
-
- print element\n
-
- This is similar to
- for (i 0 i lt array i)
-
- print arrayi\n
-
41Sorting with Foreach
- The sort function sorts the array and returns the
list in sorted order. - Example
- _at_array( Larry, Curly, Moe)
- foreach element (sort _at_array)
-
- print element
-
- Prints the elements in sorted order
- Curly Larry Moe
42Exercise Sorting According to Multiple Criterion
- Use the following initialization to sort
individuals by age and then by income - Syntax
- _at_sortedArray sort numeric _at_unsortedArray
- sub numeric
-
- return a ltgt b
-
- Data
- _at_index(0,1,2,3,4)_at_name(V,W,X,Y,Z)
_at_age(10,20, 15, 20, 10)_at_income(100,670,
280,800,400) - Output
- Name X Age A Income I
- Tip
- -Sort the index, using information contained in
the other arrays.
43Exercise Sorting According to Multiple Criterion
- _at_index(0,1,2,3,4,5)_at_name(V,W,X,Y,Z)
_at_age(10,20, 15, 20, 10)_at_income(100,670,
280,800,400)foreach i ( sort my_numeric
_at_index) print namei agei
incomei sub my_numeric -
- if (agea ageb)
- return incomealtgtincomeb
- else
- return agealtgtageb
-
44 45Strings to Arrays split
- Split a string into words and put into an array
- _at_array split( //, LarryCurlyMoe )
- _at_array (Larry, Curly, Moe)
- creates the same array as we saw
previously -
- Split into characters
- _at_stooge split( //, curly )
- array _at_stooge has 5 elements c, u, r, l, y
46Split cont..
- Split on any character
- _at_array split( //, 10203040)
- array has 4 elements 10, 20, 30, 40
- Split on Multiple White Space
- _at_array split(/\s/, this is a test
- array has 4 elements this, is, a, test
- More on \s later
47Arrays to Strings
- Array to space separated string
- _at_array (Larry, Curly, Moe)
- string join( , _at_array)
- string LarryCurlyMoe
- Array of characters to string
- _at_stooge (c, u, r, l, y)
- string join( , _at_stooge )
- string curly
48Joining Arrays cont
- Join with any character you want
- _at_array ( 10, 20, 30, 40 )
- string join( , _at_array)
- string 10203040
- Join with multiple characters
- _at_array 10, 20, 30, 40)
- string join(-gt, _at_array)
- string 10-gt20-gt30-gt40
49Arrays as Stacks and Lists
- To append to the end of an array
- _at_array ( Larry, Curly, Moe )
- push (_at_array, Shemp )
- print array3 prints Shemp
- To remove the last element of the array (LIFO)
- elment pop _at_array
- print element prints Shemp
- _at_array now has the original elements
- (Larry, Curly, Moe)
50Arrays as Stacks and Lists
- To prepend to the beginning of an array
- _at_array ( Larry, Curly, Moe )
- unshift _at_array, Shemp
- print array3 prints Moe
- print array0 prints Shemp
- To remove the first element of the array
- element shift _at_array
- print element prints Shemp
- The array now contains only
- Larry, Curly, Moe
51Exercise Spliting
- Instructions
- Remove
- shift beginning, pop end
- Add
- 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
couplesInto five couples were administered
the enquiry 1.
52Exercise Spliting
- Use split, shift and push to turn the following
strings0 The enquiry 1 was administered
to five coupless1 The enquiry 2 was
administered to six coupless2 The enquiry
3 was administered to eigh couples - foreach s(_at_s)
-
- _at_s2split (/was administered to/, s)
- new_ss21 were admimistered s20
- print new_s\n
-
53 54Multi Dimensional Arrays
- Better use Hash tables (cf later)
- If you need to
- _at_tab(Monday,Tuesday,
- Morning,Afternoon,Evening)
- atab00 a Monday
- tab2(midnight, Twelve)
- tab2\_at_tab2 integrate tab2 as the last row
of tab
55Thank you ?