Perl Tutorial-Part II CSCI 3136 Principles of Programming and - - PowerPoint PPT Presentation

perl tutorial part ii
SMART_READER_LITE
LIVE PREVIEW

Perl Tutorial-Part II CSCI 3136 Principles of Programming and - - PowerPoint PPT Presentation

Perl Tutorial-Part II CSCI 3136 Principles of Programming and Languages Slides mainly taken from Perl Programming, Quentin Smith 1 http://stuff.mit.edu/iap/perl/ Outline Run a Perl Program Data Types Context Operators Flow


slide-1
SLIDE 1

Perl Tutorial-Part II

CSCI 3136 Principles of Programming and Languages

1 Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/

slide-2
SLIDE 2

Outline

  • Run a Perl Program
  • Data Types
  • Context
  • Operators
  • Flow Control
  • Subroutines
  • References
  • Files
  • Regular Expressions

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 2

slide-3
SLIDE 3

Run a Perl Program

  • on bluenose:

– perl hello.pl – Add “#!/usr/bin/perl” to the first line of hello.pl – chmod a+x hello.pl – ./hello.pl

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 3

slide-4
SLIDE 4

Data Types

  • Scalar

– Singles values – Name preceded by a $ character

  • Arrays

– Multiple ordered values – Name preceded by a @ character

  • Hashes

– Multiple unordered values – Name preceded by a % character

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 4

slide-5
SLIDE 5

Context

  • Context determines how variables and values

are evaluated

  • Numeric context
  • String context
  • Boolean context
  • Determined by operators

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 5

slide-6
SLIDE 6

Operators

  • Numeric

– ++, --, +, -, *, /, +=, *=, >>, <<

  • String

– Concatenation (.), repetition (x), assignment (.=, x=)

  • Quoting

– qq (“), q (‘), qx(`), qw, pattern matching

  • Boolean

– <, >, ==, !=, =>, <= – lt, gt, eq, ne, le, ge – &&, ||, !, and, or, not – ? :

  • List

– sort, reverse, push/pop, unshift/shift, split/join, grep, map

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 6

slide-7
SLIDE 7

Flow Control

  • Flow control is expressive in Perl
  • Conditional statements

– if – unless

  • Loop statements

– while – until – for – foreach

  • Modifiers

– Simple statements may be modified

  • See perldoc perlsyn for complete syntax

7 Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/

slide-8
SLIDE 8

Conditional Statements

  • Conditional statements provide boolean

context

  • if statement controls the following block

– if, elsif, else – Yes, that does say elsif not else if

  • unless is opposite of if

– Equivalent to if (not $boolean) – unless, elsif, else – There is no elsunless, thankfully.

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 8

slide-9
SLIDE 9

Conditional Statements

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 9

my ($a, $b) = (0, 1); if (!$a && !$b) {print "Neither\n";} # Conventional if (not $a and not $b) {print "Neither\n";} # Same, but in English if (not ($a or $b)) {print "Neither\n";} # Same, but parentheses unless ($a or $b) {print "Neither\n";} # Same, but clearest ($a,$b) = (1,0); unless($a) { print “a is not true”; }elsif($b) { print “b is true”; }else{ print “a is true but b is not true”; }

slide-10
SLIDE 10

Loop Statements

  • Loop statements provide a boolean context
  • while

– Loops while boolean is true

  • until

– Loops until boolean is true – Opposite of while

  • do

– At least one loop, then depends on while or until

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 10

slide-11
SLIDE 11

Loop Statements

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 11

my $counter = 10; while ($counter >= 0) { print $counter.”,”; $counter--; } Output: 10,9,8,7,6,5,4,3,2,1,0, $counter = 5; until ($counter < 0) { print $counter.”,” $counter--; } Output: 5,4,3,2,1,0, $counter = 0; do { print $counter.”,” $counter--; } while ($counter >= 0); Output: 0,

slide-12
SLIDE 12

Loop Statements

  • for

– Like C, C++, Java: for (initialization; condition; increment)

  • foreach

– Iterates over a list or array

  • Good to localize loop variables with my

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 12

slide-13
SLIDE 13

Loop Statements

  • Example

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 13

for (my $i = 10; $i >= 0; $i--) { print "$i,"; # Countdown } Output: 10,9,8,7,6,5,4,3,2,1,0, foreach my $i (reverse 0..10) { print "$i,\n"; # Same } Output: 10,9,8,7,6,5,4,3,2,1,0, %hash = (dog => "lazy", fox => "quick"); foreach my $key (keys %hash) { print "The $key is $hash{$key}.\n"; # Print out hash pairs } Output: The fox is quick. The dog is lazy.

slide-14
SLIDE 14

Modifiers

  • Simple statements can take single modifiers

– Places emphasis on the statement, not the control – Can make programs more legible – Parentheses usually not needed – Good for setting default values – Valid modifiers are if, unless, while, until, foreach

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 14

slide-15
SLIDE 15

Modifiers

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 15

my $default = 0; my $a = $default unless defined $a; my $b = 3; $b = $default unless defined $b; print “$a,$b\n”; Output: 0,3 my $balance = 5000; $balance += $deposit if $deposit; print “$balance\n”; Output: 5000 my withdrawal = 300; $balance -= $withdrawal if $withdrawal and $withdrawal <= $balance; Print “$balance\n”; Output: 4700

slide-16
SLIDE 16

Subroutines

  • Subs group related statements into a single

task

  • Perl allows both declared and anonymous

subs

  • Perl allows various ways of handling

arguments

  • Perl allows various ways of calling subs
  • perldoc perlsub gives complete description

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 16

slide-17
SLIDE 17

Declaring Subroutines

  • Subroutines are declared with the sub keyword
  • Subroutines return values

– Explicitly with the return command – Implicitly as the value of the last executed statement

  • Return values can be a scalar or a flat list

– wantarray describes what context was used – Unused values are just lost

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 17

slide-18
SLIDE 18

Declaring Subroutines

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 18

sub ten { @array = (1..10); return wantarray() ? @array : 100; } @ten = ten(); # (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) $ten = ten(); # 100 ($ten) = ten(); # (1) ($one, $two) = ten(); # (1, 2)

  • sub ten{

@array = (1..10); return @array; } @ten = ten(); # (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) $ten = ten(); # 10

slide-19
SLIDE 19

Handling Arguments

  • Two common means of passing arguments to

subs

– Pass by value – Pass by reference – Perl allows either

  • Arguments are passed into the @_ array

– @_ is the "fill in the blanks" array – Usually should copy @_ into local variables

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 19

slide-20
SLIDE 20

Handling Arguments

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 20

sub add_one { # Like pass by value my ($n) = @_; # Copy first argument return ($n + 1); # Return 1 more than argument } sub plus_plus { # Like pass by reference $_[0] = $_[0] + 1; # Modify first argument } # no return statement my ($a, $b) = (10, 0); add_one($a); # Return value is lost, nothing changes $b = add_one($a); # $a is 10, $b is 11 plus_plus($a); # Return value lost, but a now is 11 $b = plus_plus($a); # $a and $b are 12

slide-21
SLIDE 21

Calling Subroutines

  • Subroutine calls usually have arguments in

parentheses

– Parentheses are not needed if sub is declared first – But using parentheses is often good style

  • Subroutine calls may be recursive
  • Subroutines are another data type

– Name may be preceded by an & character – & is not needed when calling subs

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 21

slide-22
SLIDE 22

Calling Subroutines

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 22

print factorial(5) . "\n"; # Parentheses required sub factorial { my ($n) = @_; return $n if $n <= 2; $n * factorial($n - 1); } print ((factorial 5) . "\n"); # Parentheses around argument not required, # but need to ensure there are no extra arguments print &factorial(5) . "\n"; # Neither () nor & required

slide-23
SLIDE 23

Subroutines

  • Example:

– Declare subroutine – Copy arguments – Check arguments – Perform computation – Return results

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 23

slide-24
SLIDE 24

Subroutines

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 24

sub fibonacci { my ($n) = @_; die "Number must be positive" if $n <= 0; return 1 if $n <= 2; return (fibonacci($n-1) + fibonacci($n-2)); } foreach my $i (1..5) { my $fib = fibonacci($i); print "fibonacci($i) is $fib\n"; } fibonacci(1) is 1 fibonacci(2) is 1 fibonacci(3) is 2 fibonacci(4) is 3 fibonacci(5) is 5

slide-25
SLIDE 25

References

  • References indirectly refer to other data
  • Dereferencing yields the data
  • References allow you to create anonymous

data

  • References allow you to build hierarchical data

structures

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 25

my @fruit = qw(apple banana cherry); my $fruitref = \@fruit;

slide-26
SLIDE 26

Dereferencing Data

  • Dereferencing yields the data

– Appropriate symbol dereferences original data – Arrow operator (->) dereferences items

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 26

my @fruit = qw(apple banana cherry); my $fruitref = \@fruit; print "I have these fruits: @$fruitref.\n"; print "I want a $fruitref->[1].\n"; Output: I have these fruits: apple banana cherry. I want a banana.

slide-27
SLIDE 27

Anonymous Data

  • References allow you to create anonymous

data

– Referencing arrays and hashes are common – Build unnamed arrays with brackets ([]) – Build unnamed hashes with braces ({})

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 27

slide-28
SLIDE 28

Anonymous Data

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 28

my $fruits = ["apple", "bananas", "cherries"]; #my @fruitarr = ("apple", "bananas", "cherries"); #my $fruits = \@fruits my $wheels = {unicycle => 1, bike => 2, tricycle => 3, car => 4, semi => 18}; #my %wheelhash = (unicycle => 1, bike => 2, tricycle => 3, car => 4, semi => 18); #my $wheels = \$wheelhash; print "A car has $wheels->{car} wheels.\n"; Output: A car has 4 wheels.

slide-29
SLIDE 29

Hierarchical Data

  • References allow you to build hierarchical data

structures

– Arrays and hashes can only contain scalars – But a reference is a scalar, even if it refers to an array or a hash – Don't even need the arrow operator for these structures

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 29

slide-30
SLIDE 30

Hierarchical Data

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 30

my $fruits = ["apple", "bananas", "cherries"]; my $veggies = ["spinach", "turnips"]; my $grains = ["rice", "corn"]; my @shopping_list = ($fruits, $veggies, $grains); print "I should remember to get $shopping_list[2]->[1].\n"; print "I should remember to get $shopping_list[0][2].\n"; Output: I should remember to get corn. I should remember to get cherries.

slide-31
SLIDE 31

Files

  • Access to files is similar to shell redirection

– < for input, > for output, >> for append

  • Standard files

– STDIN, STDOUT, STDERR

  • Reading from files
  • Writing to files
  • Pipes
  • File checks

– exist, read, write, etc.

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 31

slide-32
SLIDE 32

File Access

  • Access to files is similar to shell redirection

– open allows access to the file – Redirect characters (<, >) define access type

  • Can read, write, append, read & write, etc.

– Filehandle refers to opened file

  • Variable without any preceded character
  • Capital characters by convention

– close stops access to the file – $! contains IO error messages – perldoc perlopentut has complete description

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 32

slide-33
SLIDE 33

File Access

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 33

  • pen INPUT, "< datafile" or die "Can't open input file: $!";
  • pen OUTPUT, "> outfile " or die "Can't open output file: $!";
  • pen LOG, ">> logfile " or die "Can't open log file: $!";
  • pen RWFILE, "+< myfile " or die "Can't open file: $!";

close INPUT;

slide-34
SLIDE 34

Standard Files

  • Standard files are opened automatically

– STDIN is standard input – STDOUT is standard output – STDERR is standard error output – Can re-open these for special handling – <> uses standard input by default – print uses standard output by default – die and warn use standard error by default

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 34

slide-35
SLIDE 35

Standard Files

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 35

print STDOUT "Hello, world.\n"; # STDOUT not needed

  • pen STDERR, ">> logfile" or die "Can't redirect errors to log: $!";

print STDERR "Oh no, here's an error message.\n"; warn "Oh no, here's another error message.\n"; close STDERR;

slide-36
SLIDE 36

Reading from Files

  • Reading from files

– Input operator <> reads one line from the file, including the newline character – <> reads from STDIN by default – chomp will remove newline if you want – Can modify input recorder separator $/ to read characters, words, paragraphs, records, etc.

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 36

slide-37
SLIDE 37

Reading from Files

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 37

print "What type of pet do you have? "; my $pet = <STDIN>; # Read a line from STDIN, say parrot #$pet is “parrot\n” chomp $pet; # Remove newline, $pet contains “parrot” print "Enter your pet's name: "; my $name = <>; # STDIN is optional chomp $name; print "Your pet $pet is named $name.\n"; Output: What type of pet do you have? parrot Enter your pet's name: Polly Your pet parrot is named Polly.

slide-38
SLIDE 38

Reading from Files

  • Reading from files

– Easy to loop over entire file – Loops will assign to $_ by default – Be sure that the file is open for reading first

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 38

slide-39
SLIDE 39

Reading from Files

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 39

  • pen CUSTOMERS, "< mailing_list" or die "Can't open input file: $!";

while (my $line = <CUSTOMERS>) { my @fields = split(":", $line); # Fields separated by colons print "$fields[1] $fields[0]\n"; # Display selected fields print "$fields[3], $fields[4]\n"; print "$fields[5], $fields[6] $fields[7]\n"; } print while <>; # cat utility in Unix/Linux print STDOUT $_ while ($_ = <STDIN>); # same, but more verbose Output: Last name:First name:Age:Address:Apartment:City:State:ZIP Smith:Al:18:123 Apple St.:Apt. #1:Cambridge:MA:02139 Al Smith 123 Apple St., Apt. #1 Cambridge, MA 02139

slide-40
SLIDE 40

Writing to Files

  • Writing to files

– print writes to a file – print writes to a STDOUT by default – Be sure that the file is open for writing first

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 40

slide-41
SLIDE 41

Writing to Files

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 41

  • pen CUSTOMERS, "< mailing_list" or die "Can't open input file: $!";
  • pen LABELS, "> labels" or die "Can't open output file: $!";

while (my $line = <CUSTOMERS>) { my @fields = split(":", $line); print LABELS "$fields[1] $fields[0]\n"; print LABELS "$fields[3], $fields[4]\n"; print LABELS "$fields[5], $fields[6] $fields[7]\n"; }

slide-42
SLIDE 42

Pipes

  • Pipes

– Pipes redirect input from or output to another process – Just like shell redirection, pipes act like normal files

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 42

# Use another process as input

  • pen INPUT, "ps aux |" or die "Can't open input command: $!";

# Print labels to printer instead of to a file

  • pen LABELS, "| lpr" or die "Can't open lpr command: $!";
slide-43
SLIDE 43

File Checks

  • File checks

– File test operators check if a file exists, is readable or writable, etc. – -e tests if file is exists – -r tests if file is readable – -w tests if file is writable – -x tests if file is executable – -l tests if file is a symlink – -T tests if file is a text file – perldoc perlfunc lists more

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 43

slide-44
SLIDE 44

File Checks

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 44

my $filename = "pie_recipe"; if (-r $filename) {

  • pen INPUT, “< $filename" or die "Can't open $filename: $!";

}else { print "The file $filename is not readable.\n"; }

  • my $filename = “log_file";

if (-w $filename) {

  • pen INPUT, “> $filename" or die "Can't open $filename: $!";

}else { print "The file $filename is not writable.\n"; }

slide-45
SLIDE 45

Regular Expressions

  • Regexes perform textual pattern matching
  • Regexes may be quoted in several ways
  • Regexes are their own mini-language

– Match letters, numbers, other characters – Exclude certain characters from matches – Match boundaries between types of characters – Group subpatterns – Match repetitions

  • Perl has several regex operators

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 45

slide-46
SLIDE 46

Regular Expressons

  • Regexes perform textual pattern matching

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 46

my $string = "Did the fox jump over the dogs?"; #contain the letters "dog" in order? print "1: $string\n" if $string =~ /dog/; # matches #not contain the letter "z"? print "2: $string\n" if $string !~ /z/; # matches #begin with the letters "Y" or "y"? print "3: $string\n" if $string =~ /^[Yy]/; #end with a question mark? print "4: $string\n" if $string =~ /\?$/; # matches #contain only letters? print "5: $string\n" if $string =~ /^[a-zA-Z]*$/; #contain only digits? print "6: $string\n" if $string =~ /^\d*$/;

slide-47
SLIDE 47

Regular Expressions

  • Regexes may be quoted in several ways

– Regex quotes are usually slashes (/regex/) – May use other quotes with the match operator m – Use other quotes when matching slashes (m[/]) – Comparison operators (=~, !~) test for matches

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 47

my $string = "Did the fox jump over the dogs?"; print "1: $string\n" if $string =~ /dog/; # matches print "2: $string\n" if $string =~ m/dog/; # matches print "3: $string\n" if $string =~ m(dog); # matches print "4: $string\n" if $string =~ m|dog|; # matches

slide-48
SLIDE 48

Regular Expressions

  • Regexes are their own mini-language

– Match letters, numbers, other characters – Exclude certain characters from matches – Character classes (in []) denote a possible set of characters to match – Negate a character classes with a carat ([^abc]) – Provided character classes include:

  • \d, \D for digits, non-digits, \d is the same as [1-9]
  • \w, \W for word and non-word characters (letters, digits,

underscore), \w is the same as [a-zA-Z1-9_]

  • \s, \S for white-space and non-space characters
  • . for any character except newline

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 48

slide-49
SLIDE 49

Regular Expressions

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 49

my $string = "Did the fox jump over the dogs?"; print "1: $string\n" if $string =~ m/[bdl]og/; # bog, dog, log print "2: $string\n" if $string =~ m/dog[^s]/; # no match print "3: $string\n" if $string =~ m/\s\w\w\wp\s/; # matches

slide-50
SLIDE 50

Regular Expressions

  • Match boundaries between types of

characters

– ^ matches the start of the string – $ matches the end of the string – \b matches a word boundary

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 50

my $string = "Did the fox jump over the dogs?"; print "1: $string\n" if $string =~ m/^[Yy]/; # no match print "2: $string\n" if $string =~ m/\?$/; # match print "3: $string\n" if $string =~ m/the\b/; # match

slide-51
SLIDE 51

Regular Expressions

  • Quantify matches

– * matches the preceding character 0 or more times – + matches the preceding character 1 or more times – ? matches the preceding character 0 or once – {4} matches exactly 4 times – {3,6} matches 3 to 6 times

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 51

slide-52
SLIDE 52

Regular Expressions

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 52

my $string = "Did the fox jump over the dogs?"; print "1: $string\n" if $string =~ m/z*/; # matches print "2: $string\n" if $string =~ m/z+/; # no match print "3: $string\n" if $string =~ m/\b\w{4}\b/; # matches "jump“ print “4: $string\n” if $string =~ m/H?/; # matches print “5: $string\n” if $string =~ m/\b\w{2,6}\b/; # matches, # any word whose length is between 2 and 6

slide-53
SLIDE 53

Regular Expressions

  • Group subpatterns

– () group a subpattern

  • Match repetitions

– \1, \2 refer to the first and second groups

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 53

my $string = "Did the fox jump over the dogs?"; print "1: $string\n" if $string =~ m/(fox){2}/; # "foxfox" print "2: $string\n" if $string =~ m/(the\s).*\1/; # matches

slide-54
SLIDE 54

Regular Expressions

  • Perl has several regex operators

– m just matches, providing boolean context – s/match/replacement/ substitutes – tr/class/replacement/ transliterates

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 54

my $string = "Did the fox jump over the dogs?"; $string =~ s/dog/cat/; # substitute "cat" for "dog" $string =~ s(fox)(kangaroo); # substitute "kangaroo" for "fox" print "$string\n"; $string =~ tr/a-z/n-za-m/; # Rot13 print "$string\n"; Output: Did the kangaroo jump over the cats? Dvq gur xnatnebb whzc bire gur pngf?

slide-55
SLIDE 55

Regular Expressions

  • Perl has several regex modifiers

– g global: allows for multiple substitutions – i case insensitive matching – s treat string as one line – m treat string as multiple lines

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 55

slide-56
SLIDE 56

Regular Expresssions

  • Example:

Slides mainly taken from Perl Programming, Quentin Smith http://stuff.mit.edu/iap/perl/ 56

my $breakfast = 'Lox Lox Lox lox and bagels'; $breakfast =~ s/Lox //g; print "$breakfast\n"; my $paragraph = "First Line\nSecond Line\nThird Line\n"; my ($first, $second) = ($paragraph =~ /(^.*$)\n(^.*$)/m); print "$first, $second\n"; Output: lox and bagels First Line, Second Line