Top Banner
Introduction to Introduction to Perl Programming Perl Programming Morris Law Morris Law December 8, 2012 December 8, 2012
30

Introduction to Perl Programming Morris Law December 8, 2012.

Dec 31, 2015

Download

Documents

Justin Sullivan
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to Perl Programming Morris Law December 8, 2012.

Introduction to Perl Introduction to Perl ProgrammingProgramming

Introduction to Perl Introduction to Perl ProgrammingProgramming

Morris LawMorris Law

December 8, 2012December 8, 2012

Page 2: 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

Page 3: Introduction to Perl Programming Morris Law December 8, 2012.

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

Page 4: Introduction to Perl Programming Morris Law December 8, 2012.

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

Page 5: Introduction to Perl Programming Morris Law December 8, 2012.

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

Page 6: Introduction to Perl Programming Morris Law December 8, 2012.

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

Page 7: Introduction to Perl Programming Morris Law December 8, 2012.

Install and run DWIMPERL based on Strawberry

PERL• Download from

http://dwimperl.com/windows.html

• Come with Padre, the Perl IDE

Page 8: Introduction to Perl Programming Morris Law December 8, 2012.

PERL numbers• Number

– 255 (decimal)– 0377 (octal)– 0b1111111 (binary)– 0xFF (hexidecimal)

• Example#!/usr/bin/perl#goodnums.plxuse warnings;print 255, "\n";print 0377, "\n";print 0b11111111, "\n";print 0xFF, "\n";

goodnums.plx

Page 9: Introduction to Perl Programming Morris Law December 8, 2012.

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-documentprint<<EOF;

Dear Mary, I am demonstrating the usage of PERL

EOF

Page 10: Introduction to Perl Programming Morris Law December 8, 2012.

PERL operators• Arithmetics

+,-,*,/,( ), **, %

• Bitwise&, |, ^, ~

• Comparison==, !=, <, >, >=, <=<=>gt, ge, eq, lt, le, cmp

• Boolean&&, ||, !

• Repetitionx3, x4

Page 11: Introduction to Perl Programming Morris Law December 8, 2012.

PERL operators (cont.)• Ternary operator

a ? b : c

• Range operator…

• Shift<<, >>

• regular expression=~, !~a <opr>= b where <opr> = +,-,*,\,/

Page 12: Introduction to Perl Programming Morris Law December 8, 2012.

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>

Page 13: Introduction to Perl Programming Morris Law December 8, 2012.

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]; # Wedfor $day (@a) { print $day , "\t";}for (0 … $#array2) {print "Hello World\n"}

for (@x){$_*= 2} print "After : @x\n";

array2.plx

Page 14: Introduction to Perl Programming Morris Law December 8, 2012.

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

Page 15: Introduction to Perl Programming Morris Law December 8, 2012.

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";

Page 16: Introduction to Perl Programming Morris Law December 8, 2012.

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

Page 17: Introduction to Perl Programming Morris Law December 8, 2012.

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

Page 18: Introduction to Perl Programming Morris Law December 8, 2012.

PERL control flow (cont)

• while ( <condition> ) { <action> }• do { <action> } while (<condition> );• for ( <loop range> ) { <action> }

#testfor1.plxprint "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

Page 19: Introduction to Perl Programming Morris Law December 8, 2012.

PERL control flow (cont)

• foreach# foreach1.plxuse strict;my @collection = qw/hat shoes shirts shorts/;foreach my $item (@collection) {print "$item\n";}

# foreach2.plxuse strict;my %table = qw/schmoe joe smith john simpson bart/;my($key, $value); # Declare two variables at oncewhile ( ($key, $value) = each(%table) ) { print "$key and $value are friend\n";}

Page 20: Introduction to Perl Programming Morris Law December 8, 2012.

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.

Page 21: Introduction to Perl Programming Morris Law December 8, 2012.

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; }}

Page 22: Introduction to Perl Programming Morris Law December 8, 2012.

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 argumentuse 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");

Page 23: Introduction to Perl Programming Morris Law December 8, 2012.

PERL subroutine• subroutine accept as many arguments

# greeting3.plxuse 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");

Page 24: Introduction to Perl Programming Morris Law December 8, 2012.

PERL file# numbering lines# nl.plxuse warnings;use strict;

open FILE, "example.txt" or die $!;my $lineno = 1;

while (<FILE>) { print $lineno++; print ": $_";}

nl.plx

Page 25: Introduction to Perl Programming Morris Law December 8, 2012.

Perl file• A special notation <> stands for <ARGV>, argument input

# Accept multiple files# nl2.plxuse warnings;use strict;

my $lineno = 1;

while (<>) { print $lineno++; print ": $_";}

• Run it with perl nl2.plx example.txt

nl2.plx

Page 26: Introduction to Perl Programming Morris Law December 8, 2012.

Perl file# nl3.plxuse 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

Page 27: Introduction to Perl Programming Morris Law December 8, 2012.

PERL input record separator $/

# fortune.plxuse 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

Page 28: Introduction to Perl Programming Morris Law December 8, 2012.

PERL file input & output# copy.plxuse 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

Page 29: Introduction to Perl Programming Morris Law December 8, 2012.

More resources from More resources from CPANCPAN

More resources from More resources from CPANCPAN

using CPAN Explorer in DWIMusing CPAN Explorer in DWIM

Page 30: Introduction to Perl Programming Morris Law December 8, 2012.

Thanks!Thanks!Thanks!Thanks!Any questions?Any questions?

[email protected]@hkbu.edu.hk