Short Perl Tutorial: Instructor: Rada Mihalcea University of Antwerp
Short Perl Tutorial: Instructor: Rada Mihalcea University of Antwerp
About Perl
1987
Larry Wall Develops PERL October 18 Perl 3.0 is released under the GNU Protection License March 21 Perl 4.0 is released under the GPL and the new Perl Artistic License Perl 5.14 PERL is not officially a Programming Language per se. Walls original intent was to develop a scripting language more powerful than Unix Shell Scripting, but not as tedious as C. PERL is an interpreted language. That means that there is no explicitly separate compilation step. Rather, the processor reads the whole file, converts it to an internal form and executes it immediately. P.E.R.L. = Practical Extraction and Report Language
Slide 1
1989
1991
Now
Variables
A variable is a name of a place where some information is stored. For example:
Slide 2
Operations on numbers
Perl contains the following arithmetic operators: +: sum -: subtraction *: product /: division %: modulo division **: exponent Apart from these operators, Perl contains some built-in arithmetic functions. Some of these are mentioned in the following list: abs($x): absolute value int($x): integer part rand(): random number between 0 and 1 sqrt($x): square root
Slide 3
# count the number of lines in a file open INPUTFILE, <$myfile; (-r INPUTFILE) || die Could not open the file $myfile\n; $count = 0; while($line = <INPUTFILE>) { $count++; } print $count lines in file $myfile\n; # open for writing open OUTPUTFILE, >$myfile;
Slide 4
Conditional structures
# determine whether number is odd or even
print "Enter number: "; $number = <>; chomp($number); if ($number-2*int($number/2) == 0) { print "$number is even\n"; } elsif (abs($number-2*int($number/2)) == 1) { print "$number is odd\n"; } else { print "Something strange has happened!\n"; }
Slide 5
Truth expressions
three logical operators: and: and (alternative: &&) or: or (alternative: ||) not: not (alternative: !)
Slide 6
Iterative structures
#print numbers 1-10 in three different ways $i = 1; while ($i<=10) { print "$i\n"; $i++; } for ($i=1;$i<=10;$i++) { print "$i\n"; }
next; # C continue;
Exercise: Read ten numbers and print the largest, the smallest and a count representing how many of them are dividable by three.
Slide 7
Slide 8
Slide 9
Slide 10
Examples
# replace first occurrence of "bug" $text =~ s/bug/feature/; # replace all occurrences of "bug" $text =~ s/bug/feature/g; # convert to lower case $text =~ tr/[A-Z]/[a-z]/;
Regular expressions
Examples: \b: word boundaries 1. Clean an HTML formatted text \d: digits \n: newline \r: carriage return 2. Grab URLs from a Web page \s: white space characters \t: tab \w: alphanumeric characters 3. Transform all lines from a file into ^: beginning of string lower case $: end of string .: any character [bdkp]: characters b, d, k and p [a-f]: characters a to f [^a-f]: all characters except a to f abc|def: string abc or string def [:alpha:],[:punct:],[:digit:], - use inside character class e.g., [[:alpha:]] *: zero or more times +: one or more times ?: zero or one time {p,q}: at least p times and at most q times {p,}: at least p times {p}: exactly p times
Slide 12
Split function
$string = "Jan Piet\nMarie \tDirk"; @list = split /\s+/, $string; # yields ( "Jan","Piet","Marie","Dirk" ) $string = " Jan Piet\nMarie \tDirk\n"; # watch out, empty string at the begin and end!!! @list = split /\s+/, $string; # yields ( "", "Jan","Piet","Marie","Dirk", "" ) $string = "Jan:Piet;Marie---Dirk"; # use any regular expression... @list = split /[:;]|---/, $string; # yields ( "Jan","Piet","Marie","Dirk" ) $string = "Jan Piet"; # use an empty regular expression to split on letters @letters= split //, $string; # yields ( "J","a","n"," ","P","i","e","t")
Example:
1. Tokenize a text: separate simple punctuation (, . ; ! ? ( ) ) 2. Add all the digits in a number
Slide 14
pop ARRAY does the opposite of push. it removes the last item of its argument list and returns it. if the list is empty it returns undef. @array = ("an","bert","cindy","dirk"); $item = pop @array; # $item is "dirk" and @array is ( "an","bert","cindy")
shift ARRAY works on the left end of the list, but is otherwise the same as pop. unshift ARRAY LIST puts stuff on the left side of the list, just as push does for the right side.
Slide 16
Slide 18
Slide 19
Hashes (contd)
Examples $wordfrequency{"the"} = 12731; # creates key "the", value 12731 $phonenumber{"An De Wilde"} = "+31-20-6777871"; $index{$word} = $nwords; $occurrences{$a}++; # if this is the first reference, # the value associated with $a will # be increased from 0 to 1
Slide 20
Operations on Hashes
- keys HASH returns a list with only the keys in the hash. As with any list, using it in a scalar context returns the number of keys in that list.
- values HASH returns a list with only the values in the hash, in the same order as the keys returned by keys.
foreach $key (sort keys %hash ){ push @sortedlist, ($key , $hash{$key} ); print "Key $key has value $hash{$key}\n"; }
Slide 21
Operations on Hashes
reverse the direction of the mapping, i.e. construct a hash with keys and values swapped: %backwards = reverse %forward;
(if %forward has two identical values associated with different keys, those will end up as only a single element in %backwards)
Slide 22
$matrix[$i][$j] = $x; $lexicon1{"word"}[1] = $partofspeech; $lexicon2{"word"}{"noun"} = $frequency; Array of arrays @matrix = ( # an array of references to anonymous arrays [1, 2, 3], [4, 5, 6], [7, 8, 9] );
Slide 23
Multidimensional structures
Hash of arrays %lexicon1 = ( the => [ "Det", 12731 ], man => [ "Noun", 658 ], with => [ "Prep", 3482 ] ); Hash of hashes %lexicon2 = (
numbers
the => { Det => 12731 }, man => { Noun => 658 , Verb => 12 }, with => { Prep => 3482 } );
Slide 24
Programming Example
A program that reads lines of text, gives a unique index number to each word and counts the word frequencies
#!/usr/local/bin/perl # read all lines in the input
$nwords = 0; while(defined($line = <>)){ # cut off leading and trailing whitespace $line =~ s/^\s*//; $line =~ s/\s*$//; # and put the words in an array @words = split /\s+/, $line; if(!@words){ # there are no words? next; } # process each word... while($word = pop @words){ # if it's unknown assign a new index if(!exists($index{$word})){ $index{$word} = $nwords++; } # always update the frequency $frequency{$word}++; } } # now we print the words sorted foreach $word ( sort keys %index ){ print "$word has frequency $frequency{$word} and index $index{$word}\n"; }
Slide 25
A note on sorting
If we would like to have the words sorted by their frequency instead of by alphabet, we need a construct that imposes a different sort order. sort function can use any sort order that is provided as an expression. - the usual alphabetical sort order: sort { $a cmp $b } @list; !! $a and $b are placeholders for the two items from the list that are to be compared. Do not attempt to replace them with other variable names. Using $x and $y instead will not provide the same effect - a numerical sort order sort { $a <=> $b } @list; - for a reverse sort, change the order of the arguments: sort { $b <=> $a } @list; - sort the keys of a hash by their value instead of by their own identity, substitute the values for the arguments of sort: sort { $hash{$b} <=> $hash{$a} } ( keys %hash )
Slide 26
Slide 27
Variables Scope
A variable $a is used both in the subroutine and in the main part program of the program. $a = 0; print "$a\n"; sub changeA { $a = 1; } print "$a\n"; &changeA(); print "$a\n"; The value of $a is printed three times. Can you guess what values are printed? - $a is a global variable.
Slide 28
Variables Scope
Hide variables from the rest of the program using my.
Slide 29
Access the argument values inside the procedure with the special list @_.
E.g. my($number, $letter, $string) = @_; # reads the parameters from @_ - A tricky problem is passing two or more lists as arguments of a subroutine. &sub(@a,@b) the subroutine receives the two list as one big one and it will be unable to determine where the first ends and where the second starts. - pass the lists as reference arguments: &sub(\@a,\@b).
Slide 30
- Subroutines also use a list as output. # the return statement from a subroutine return(1,2); # or simply (1,2) # read the return values from the subroutine ($a,$b) = &subr().
- Read the main program arguments using $ARGC and @ARGV (same as in C)
Slide 31
Operations on an open file handle $a = <INFILE>: read a line from INFILE into $a @a = <INFILE>: read all lines from INFILE into @a $a = readdir(DIR): read a filename from DIR into $a @a = readdir(DIR): read all filenames from DIR into @a read(INFILE,$a,$length): read $length characters from INFILE into $a print OUTFILE "text": write some text in OUTFILE Close files / directories close(FILE): close a file closedir(DIR): close a directory
Slide 32
Example open(INFILE,"myfile") or die("cannot open myfile!"); Other About $_ Holds the content of the current variable Examples: while(<INFILE>) # $_ contains the current line read foreach (@array) # $_ contains the current element in @array
Slide 33