Title: Perl
1Perl
- Lecture 25
- Major parts of this lecture adapted from
http//www.scs.leeds.ac.uk/Perl/start.html
2Perl Example 1
!/usr/local/bin/perl Program to do the
obvious print 'Hello world.' Print a
message
3Comments on Hello, World
- Comments are to end of line
- Perl statements end with semicolons
- Perl is case-sensitive
- Perl is compiled and run in a single operation
4Perl Example 2
!/ex2/usr/bin/perl Remove blank lines from a
file Usage singlespace lt oldfile gt
newfile while (line ltSTDINgt) if (line
eq "\n") next print "line"
5More Perl notes
- Scalar variables start with
- Scalar variables hold strings or numbers, and
they are interchangeable - Examples
- priority 9
- priority '9'
- Array variables start with _at_
6Perl Example 3
!/usr/local/bin/perl Usage fixm ltfilenamesgt
Replace \r with \n -- replaces input
files foreach file (_at_ARGV) print
"Processing file\n" if (-e "fixm_temp")
die " File fixm_temp already exists!\n"
if (! -e file) die " No such file
file!\n" open DOIT, " tr \'\\015'
\'\\012' lt file gt fixm_temp" or die
" Can't tr '\015' '\012' lt infile gt
outfile\n" close DOIT open DOIT, " mv
-f fixm_temp file" or die " Can't mv -f
fixm_temp file\n" close DOIT
7Arithmetic in Perl
a 1 2 Add 1 and 2 and store in a a
3 - 4 Subtract 4 from 3 and store in
a a 5 6 Multiply 5 and 6 a 7 / 8
Divide 7 by 8 to give 0.875 a 9 10
Nine to the power of 10 a 5 2
Remainder of 5 divided by 2 a
Increment a and then return it a
Return a and then increment it --a
Decrement a and then return it a--
Return a and then decrement it
8String and assignment operators
a b . c Concatenate b and c a b x
c b repeated c times a b
Assign b to a a b Add b to a a
- b Subtract b from a a . b
Append b onto a
9Single and double quotes
- a 'apples'
- b 'bananas'
- print a . ' and ' . b
- prints apples and bananas
- print 'a and b'
- prints a and b
- print "a and b"
- prints apples and bananas
10Arrays
- _at_food ("apples", "bananas", "cherries")
- But
- print food1
- prints "bananas"
- _at_morefood ("meat", _at_food)
- _at_morefood ("meat", "apples", "bananas",
"cherries") - (a, b, c) (5, 10, 20)
11push and pop
- push adds one or more things to the end of a list
- push (_at_food, "eggs", "bread")
- push returns the new length of the list
- pop removes and returns the last element
- sandwich pop(_at_food)
- len _at_food returns length of _at_food
- food returns index of last element
12foreach
Visit each item in turn and call it
morsel foreach morsel (_at_food) print
"morsel\n" print "Yum yum\n"
13Tests
- "Zero" is false. This includes 0, '0', "0", '',
"" - Anything not false is true
- Use and ! for numbers, eq and ne for strings
- , , and ! are and, or, and not, respectively.
14for loops
- for loops are just as in C
- for (i 0 i lt 10 i) print
"i\n"
15while loops
!/usr/local/bin/perl print "Password? " a
ltSTDINgt chop a Remove the
newline at end while (a ne "fred") print
"sorry. Again? " a ltSTDINgt chop
a
16until loops
!/usr/local/bin/perl do print
"Password? " a ltSTDINgt chop
a while (a ne "fred")
17if statements
if (a) print "The string is not
empty\n" else print "The string is
empty\n"
18if - elsif statements
if (!a) print "The string is empty\n"
elsif (length(a) 1) print "The string
has one character\n" elsif (length(a) 2)
print "The string has two characters\n" else
print "The string has many characters\n"
19Why Perl?
- Two factors make Perl important
- Pattern matching/string manipulation
- Based on regular expressions (REs)
- REs are similar in power to those in Formal
Languages - but have many convenience features
- Ability to execute UNIX commands
- Less useful outside a UNIX environment
20Basic pattern matching
- sentence /the/
- True if sentence contains "the"
- sentence "The dog bites."if (sentence
/the/) is false - because Perl is case-sensitive
- ! is "does not contain"
21RE special characters
. Any single character except a
newline The beginning of the line or
string The end of the line or
string Zero or more of the last
character One or more of the last
character ? Zero or one of the last
character
22Square brackets
qjk Either q or j or k qjk
Neither q nor j nor k a-z Anything
from a to z inclusive a-z No lower
case letters a-zA-Z Any letter a-z
Any non-zero sequence of
lower case letters
23More special characters
\n A newline \t A tab \w Any
alphanumeric same as a-zA-Z0-9_ \W Any
non-word char same as a-zA-Z0-9_ \d Any
digit. The same as 0-9 \D Any non-digit.
The same as 0-9 \s Any whitespace
character\S Any non-whitespace character \b
A word boundary, outside only \B No
word boundary
24Quoting special characters
\ Vertical bar \ An open square
bracket \) A closing parenthesis \
An asterisk \ A carat symbol \/ A
slash \\ A backslash
25Alternatives and parentheses
jellycream Either jelly or cream (egle)gs
Either eggs or legs (da)
Either da or dada or
dadada or...
26Substitution
- is a test, as in sentence /the/
- ! is the negated test, as in sentence !
/the/ - is also used for replacement, as in
sentence /london/London/ - This is an expression, whose value is the number
of substitutions made (0 or 1)
27The _ variable
- Often we want to process one string repeatedly
- The _ variable holds the current string
- If a subject is omitted, _ is assumed
- Hence, the following are equivalent
- if (sentence /under/)
- _ sentence if (/under/) ...
28Global substitutions
- s/london/London/
- substitutes London for the first occurrence of
london in _ - s/london/London/g
- substitutes London for each occurrence of london
in _ - s/london/London/i
- case-insensitive substitution
29Remembering patterns
- The value of a substitution expression is the
number of substitutions actually made - Any part of the pattern enclosed in parentheses
is assigned to the special variables 1, 2, 3,
, 9 - In addition, during the match, the parts are also
in \1, \2, \3, , \9 - Example /(\b.\b) \1/ matches repeated words
30tr
- tr does character-by-character translation
- tr returns the number of substitutions made
- sentence tr/abc/edf/
- replaces a with e, b with d, c with f
- count (sentence tr///)
- counts asterisks
- tr/a-z/A-Z/
- converts to all uppercase
31split
- split breaks a string into parts
- info "CaineMichaelActor14, Leafy
Drive"_at_personal split(//, info) - _at_personal ("Caine", "Michael", "Actor", "14,
Leafy Drive")
32Associative arrays
- Associative arrays allow lookup by name rather
than by index - Associative array names begin with
- Example
- fruit ("apples", "red", "bananas", "yellow",
"cherries", "red") - Now, fruit"bananas" returns "yellow"
- Note braces, not parentheses
33Associative Arrays II
- Can be converted to normal arrays_at_food
fruit - Cannot index an associative array, but can use
the keys and values functionsforeach f (keys
fruit) print ("The color of f is " .
fruitf . "\n")
34Associative Arrays III
- The function each gets key-value pairs
- while ((f, c) each(fruit)) print
"f is p\n"
35Defining subroutines
- Parameters are put in the array _at__ which has
nothing to do with _ - Subroutine definition
- sub printargs print "_at__\n"
36Calling subroutines
- Subroutine calls
- printargs("perly", "king")
- Prints "perly king"
- printargs("frog", "and", "toad")
- Prints "frog and toad"
37Returning a result
- The value of a subroutine is the value of the
last expression that was evaluated
sub maximum if (_0 gt _1)
_0 else _1
biggest maximum(37, 24)
38Local variables
- _at__ is local to the subroutine, and
- so are _0, _1, _2,
- local creates local variables
39Example subroutine
sub inside local(a, b)
Make local variables (a, b)
(_0, _1) Assign values a s/
//g Strip spaces from
b s/ //g local
variables (a /b/ b /a/)
Is b inside a
or a inside
b? inside("lemon", "dole money")
true
40Perl V
- Perl 5 has modules
- Perl 5 is object oriented
41The End