310 likes | 638 Views
Introduction to Perl Programming. Morris Law December 8, 2012. Content. What is PERL? Installation and usage of PERL on Windows PERL number and strings Scalar, array and hash Operators Control Flow Regular Expression Subroutine File Use of Perl Package Manager. What is PERL?.
E N D
Introduction to Perl Programming Morris Law December 8, 2012
Content • What is PERL? • Installation and usage of PERL on Windows • PERL number and strings • Scalar, array and hash • Operators • Control Flow • Regular Expression • Subroutine • File • Use of Perl Package Manager
What is PERL? • Practical Extraction and Report Language • more than 1 way to do it • easy for human reading • highly portable • talk text • high level language • free • program code with .plx and .pl as extension on MS Windows and UNIX respectively
What is PERL? • interpreter as well as compiler • support unicode • base 16 (hex) • bundle with help:- • perldoc -f print (info) • perldoc -q reverse (faq) • perldoc Text::Wrap
PERL is free and portable • Most UNIX/Linux distribution come with PERL installed • Mac OS X already has PERL installed • Windows does not come with PERL by default. Two choices • ActiveState PERL • Strawberry PERL • Latest stable version is 5.16.2
Install and run ActiveState PERL • Download from http://www.activestate.com/activeperl/downloads • Run PERL Package Manager (PPM) to install and update standard and additional packages • Start a command line interface (cmd) • Prepare PERL source code (e.g. a.plx) • Run by > perl a.plx
Install and run DWIMPERL based on Strawberry PERL • Download from http://dwimperl.com/windows.html • Come with Padre, the Perl IDE
PERL numbers • Number • 255 (decimal) • 0377 (octal) • 0b1111111 (binary) • 0xFF (hexidecimal) • Example #!/usr/bin/perl #goodnums.plx use warnings; print 255, "\n"; print 0377, "\n"; print 0b11111111, "\n"; print 0xFF, "\n"; goodnums.plx
PERL Strings • single-quoted with no processing print '\t This is a $test \n'; • double-quoted with interpolation $test = "mid term test"; print "\t This is a $test \n"; • here-document print<<EOF; Dear Mary, I am demonstrating the usage of PERL EOF
PERL operators • Arithmetics +,-,*,/,( ), **, % • Bitwise &, |, ^, ~ • Comparison ==, !=, <, >, >=, <= <=> gt, ge, eq, lt, le, cmp • Boolean &&, ||, ! • Repetition x3, x4
PERL operators (cont.) • Ternary operator a ? b : c • Range operator … • Shift <<, >> • regular expression =~, !~ a <opr>= b where <opr> = +,-,*,\,/
PERL scalar variables ($) • scalar ($) • $user, $User, $b56, $_ my $name = "fred"; my $salutation = "Dear $name, "; print $salutation, "\n"; my $time = 8; print "This is my ${time}th time \n"; • Standard Input <STDIN> • Standard Output <STDOUT>
PERL array variable (@) • array (@) @x = (12, 34, 56); @array2 = qw/One Two Three Four/; @a = qw(Mon Tue Wed Thu Fri Sat Sun); ($mone, $mtwo) = (1, 3); ($mone, $mtwo) = ($mtwo, $mone); $a = (10, 20, 30)[0]; # 10 $a = @a[2]; # Wed for $day (@a) { print $day , "\t"; } for (0 … $#array2) {print "Hello World\n"} for (@x){$_*= 2} print "After : @x\n"; array2.plx
Use of pop and push in array • pop : remove the top element of an array • push : add elements to the top of array @a = (1 ... 6); @b = reverse (1 ... 6); push @a,@b; print @a; pop @a; print @a; reverse1.plx
operators behaviour • functions behave differently with operators • take sort as an example # sort1.plx my @unsorted = (1, 2, 11, 24, 3, 36, 40, 4); my @string = sort {$a cmp $b} @unsorted; print "String sort: @string \n"; my @number = sort {$a <=> $b} @unsorted; print "Number sort: @number \n";
PERL Hash variable (%) • Hash : associative array @array = ("Gary", "Dallas", "Lucy", "Exeter", "Ian", "Reading", "Samantha", "Oregon"); %where = @array; # # %where = (Gary => "Dallas", Lucy => "Exeter", Ian => "Reading", Samantha => "Oregon"); # %who = reverse (%where); # # %who = (Dallas => "Gary", Exeter => "Lucy", Reading => "Ian", Oregon => "Samantha" # print $where{Gary}, "\n"; print $who{Reading}, "\n"; delete $where{Lucy}; $where{Eva} = "Denver"; for (keys %where) { print "$_ lives in $where{$_}\n" } %who = reverse (%where); print $who{Denver}; print $where{Eva}; hash1.plx
PERL control flow • if { … } elsif { … } else { … } #guess.plx $password = '1234'; my $guess = <STDIN>; chomp $guess; if ($password ne $guess) { die "Go away, imposter!\n"; } else { die "Correct password!\n"; } • unless ( <condition> ) { die “message” } # rate1.plx %currency = ( China => "RMB", Japan => "Yen", UK => "Pound", US => "Dollar" ); %rate = (RMB => 0.8, Yen => 10, Pound => 15, Dollar => 7.8); $to = <STDIN>; chomp $to; unless (exists $rate{$to}) { die "I don't know anything about ${to} as a currency\n"; } # exists ($rate{to}) or die "I don't know anything about ${to} as a currency\n" print "The exchange rate of $to is $rate{$to}!"; guess.plx, rate1.plx
PERL control flow (cont) • while ( <condition> ) { <action> } • do { <action> } while (<condition> ); • for ( <loop range> ) { <action> } #testfor1.plx print "Enter number (1-3) : "; my $choice = <STDIN>; chomp $choice; for ($choice) { $_ == 1 && print "You chose number ONE\n"; $_ == 2 && print "You chose number TWO\n"; $_ == 3 && print "You chose number THREE\n"; } testfor1.plx
PERL control flow (cont) • foreach # foreach1.plx use strict; my @collection = qw/hat shoes shirts shorts/; foreach my $item (@collection) { print "$item\n"; } # foreach2.plx use strict; my %table = qw/schmoe joe smith john simpson bart/; my($key, $value); # Declare two variables at once while ( ($key, $value) = each(%table) ) { print "$key and $value are friend\n"; }
Regular Expression • RE use to describe patterns in text • a* represent zero or more ‘a’. • the * character (repeat) • ba* will match ba, baab, baaac, bc • the . character (any) • a.c will match a, a c, amc, abc, aac, apc, • the | character (or) • abc|xyz will match abc or xyz • group with () • xx(abc|xyz)*xx will match xxabcxx, xxxyzxx, xxabcxyzxx, etc.
RE – anchor and pattern matching • ^a match the line preceding with a • z$ match the line end with z • What does ^aa*$ match? • guess how ^a.*[0-9]$ match? • test with the following use strict; while ( defined($currentLine = <STDIN>) ) { if ($currentLine =~ /^aa*$/) { print $currentLine; } }
PERL subroutine • Usually PERL subroutine come in first capital • Run with or without preceding &. use strict; sub HowdyEveryone { print "Hello guys.\nWhere do you want to go with Perl today?\n"; } &HowdyEveryone • Run a subroutine with argument use strict; sub HowdyEveryone { my($name1, $name2) = @_; return "Hello $name1 and $name2.\n" . "Where do you want to go with Perl today?\n"; } print &HowdyEveryone("bart", "lisa");
PERL subroutine • subroutine accept as many arguments # greeting3.plx use strict; sub HowdyEveryone { my($greeting, @names) = @_; my $returnString; foreach my $name (@names) { $returnString .= "$greeting, $name!\n"; } return $returnString . "Where do you want to go with Perl today?\n"; } print &HowdyEveryone("How is", "bart", "lisa", "homer", "marge", "maggie");
PERL file # numbering lines # nl.plx use warnings; use strict; open FILE, "example.txt" or die $!; my $lineno = 1; while (<FILE>) { print $lineno++; print ": $_"; } nl.plx
Perl file • A special notation <> stands for <ARGV>, argument input # Accept multiple files # nl2.plx use warnings; use strict; my $lineno = 1; while (<>) { print $lineno++; print ": $_"; } • Run it with perl nl2.plx example.txt nl2.plx
Perl file # nl3.plx use warnings; use strict; my $lineno; my $current = ""; while (<>) { if ($current ne $ARGV) { $current = $ARGV; print "\n\t\tFile: $ARGV\n\n"; $lineno=1; } print $lineno++; print ": $_"; } nl3.plx
PERL input record separator $/ # fortune.plx use warnings; use strict; $/ = "\n%\n"; # input record separator open QUOTES, “bible.txt" or die $!; my @file = <QUOTES>; my $random = rand(@file); my $fortune = $file[$random]; chomp $fortune; print $fortune, "\n"; fortune.plx
PERL file input & output # copy.plx use warnings; use strict; my $source = shift @ARGV; my $destination = shift @ARGV; open IN, $source or die "Can't read source file $source: $!\n"; open OUT, ">destination" or die "Can't write on file $destination: $!\n"; print "Copying $source to $destination\n"; while (<IN>) { print OUT $_; } copy.plx
More resources from CPAN using CPAN Explorer in DWIM
Thanks! Any questions? morris@hkbu.edu.hk