111
PERL PERL Pathologically Eclectic Rubbish Pathologically Eclectic Rubbish Lister Lister

Crash Course in Perl – Perl tutorial for C programmers

Embed Size (px)

Citation preview

Page 1: Crash Course in Perl – Perl tutorial for C programmers

PERLPERL

Pathologically Eclectic Rubbish Pathologically Eclectic Rubbish ListerLister

Page 2: Crash Course in Perl – Perl tutorial for C programmers

PerlPerl

• Created by Larry Wall Created by Larry Wall in 1987in 1987

• Latest version is Latest version is 5.10.0, released on 5.10.0, released on Dec 18Dec 18thth, 2007 to , 2007 to mark 20mark 20thth anniversary anniversary

Page 3: Crash Course in Perl – Perl tutorial for C programmers

How It LooksHow It Looks

##!/!/usrusr//binbin//perl perl

$;="@{'`|;{'^'!.|-'}";$.++;$.++;$.++;$_="(.)?";/((?{$_.=$_}).)+$/;@_='~!@#$%^&*( $;="@{'`|;{'^'!.|-'}";$.++;$.++;$.++;$_="(.)?";/((?{$_.=$_}).)+$/;@_='~!@#$%^&*( )_+`-=[]\\{}|;\':",./<>? '=~/$_/;@_ _=$;=~/$_/;$_="(.)*?";/((?{$_.=$_}).)+$/;$Z-= )_+`-=[]\\{}|;\':",./<>? '=~/$_/;@_ _=$;=~/$_/;$_="(.)*?";/((?{$_.=$_}).)+$/;$Z-= $Z;"$.$."-$Z;/((?{$_ _[$z]&&!("${_[$x]}"^"${_[$y]}"^"${_ _[$z]}"^"$Z")&&($a.=$_[$x $Z;"$.$."-$Z;/((?{$_ _[$z]&&!("${_[$x]}"^"${_[$y]}"^"${_ _[$z]}"^"$Z")&&($a.=$_[$x ],$b.=$_[$y],$z++);$x++;$y+=!($x%="$.$.");$y%="$.$.";}).)+/;$_="^"^"^";$_ _=".>.\ ],$b.=$_[$y],$z++);$x++;$y+=!($x%="$.$.");$y%="$.$.";}).)+/;$_="^"^"^";$_ _=".>.\ '$_ _ _$b')".".('!\@/\"'^'}.')".']}`'; '$_ _ _$b')".".('!\@/\"'^'}.')".']}`';

print; print;

Page 4: Crash Course in Perl – Perl tutorial for C programmers

What’s So Special About It?What’s So Special About It?

• 20 years of stability. Has been in production 20 years of stability. Has been in production longer than PHP, Java and Ruby.longer than PHP, Java and Ruby.

• More than 12,000 public modules available on More than 12,000 public modules available on CPAN. Ranging from Databases to WWW.CPAN. Ranging from Databases to WWW.

• Friendly community, PerlMongers and Friendly community, PerlMongers and PerlMonks.PerlMonks.

Page 5: Crash Course in Perl – Perl tutorial for C programmers

Why You Should Use ItWhy You Should Use It

• Speed of DevelopmentSpeed of Development– Large codebase publicly availableLarge codebase publicly available– No compilation and linkage, run straight from source!No compilation and linkage, run straight from source!

• PortabilityPortability– Runs on all modern operating systems (and some Runs on all modern operating systems (and some

that are not quite… modern)that are not quite… modern)– Standard modules run identically on all supported Standard modules run identically on all supported

platformsplatforms

Page 6: Crash Course in Perl – Perl tutorial for C programmers

Why You Should Use ItWhy You Should Use It

• Powerful string processing Powerful string processing

• Wide selection of editing toolsWide selection of editing tools– Text based, so just use your vi!Text based, so just use your vi!

• It’s totally free and open sourcedIt’s totally free and open sourced

Page 7: Crash Course in Perl – Perl tutorial for C programmers

Convinced?Convinced?

Page 8: Crash Course in Perl – Perl tutorial for C programmers

Course OutlineCourse Outline

• CodeflowCodeflow

• VariablesVariables

• ConditionalsConditionals

• Sexegers (regular expressions)Sexegers (regular expressions)

• Loops and iterationsLoops and iterations

• FilesFiles

Page 9: Crash Course in Perl – Perl tutorial for C programmers

Course Outline IICourse Outline II

• Using PackagesUsing Packages

• OOP in PerlOOP in Perl

• Best PracticesBest Practices

• Where do we go from here?Where do we go from here?

Page 10: Crash Course in Perl – Perl tutorial for C programmers

CodeflowCodeflow

• Perl is an interpreter and executes Perl is an interpreter and executes statements in the order it reads themstatements in the order it reads them

• There is no entry point (no main)There is no entry point (no main)

• # comments out until the end of the line# comments out until the end of the line

Page 11: Crash Course in Perl – Perl tutorial for C programmers

Your First Perl ProgramYour First Perl Program

Page 12: Crash Course in Perl – Perl tutorial for C programmers

Get Yourself Some PerlGet Yourself Some Perl

• Two flavors of Perl are available for Two flavors of Perl are available for Windows. Both are freely downloadable:Windows. Both are freely downloadable:

– ActiveState Perl ActiveState Perl (www.activestate.com)(www.activestate.com)

• Proper installer, pre-bundled with Win32 modulesProper installer, pre-bundled with Win32 modules

– Cygwin PerlCygwin Perl• Part of Cygnus Cygwin packagePart of Cygnus Cygwin package

Page 13: Crash Course in Perl – Perl tutorial for C programmers

The BasicsThe Basics

$name = “Gil”;$name = “Gil”;

print “my name is $name!\n”;print “my name is $name!\n”;

my name is Gilmy name is Gil

print ‘my name is $name!\n’;print ‘my name is $name!\n’;

my name is $name!\nmy name is $name!\n

Page 14: Crash Course in Perl – Perl tutorial for C programmers

VariablesVariables

There are 5 data types in Perl:There are 5 data types in Perl:

1.1. ScalarScalar2.2. ArrayArray3.3. HashHash4.4. File handles and constantsFile handles and constants5.5. Subroutines (functions)Subroutines (functions)

Perl is case-sensitive!Perl is case-sensitive!

Page 15: Crash Course in Perl – Perl tutorial for C programmers

ScalarsScalars

• Variables are preceded by $Variables are preceded by $

• Scalars are single, linear values. For example:Scalars are single, linear values. For example:– $x = 16;$x = 16;– $float = 2.5;$float = 2.5;– $my_str = “hello world”;$my_str = “hello world”;– $lifeValue = 0x42;$lifeValue = 0x42;– Reference (pointer)Reference (pointer)

Perl is said to be loosely-typed, you don’t declare Perl is said to be loosely-typed, you don’t declare the type of variable. A string is defined exactly likethe type of variable. A string is defined exactly likea number.a number.

Page 16: Crash Course in Perl – Perl tutorial for C programmers

Scalar OperationsScalar Operations

$x = 3.0;$x = 3.0;

$y = 5;$y = 5;

print $x + $y; # addprint $x + $y; # add

print $x - $y; # subprint $x - $y; # sub

print $x * $y; # mulprint $x * $y; # mul

print $x ** $y; # expprint $x ** $y; # exp

print $x / $y; # divprint $x / $y; # div

print $x % $y; # modprint $x % $y; # mod

print “3” + 5; => 8print “3” + 5; => 8

print “3E5” + 1; => 300,001print “3E5” + 1; => 300,001

print “hello” + “world”; => 0print “hello” + “world”; => 0

Page 17: Crash Course in Perl – Perl tutorial for C programmers

Scalar StringsScalar Strings

Use dot (.) to concatenate stringsUse dot (.) to concatenate strings

$str = “hello “ . $name . “!”;$str = “hello “ . $name . “!”;

oror$str = “hello $name!”;$str = “hello $name!”;

Page 18: Crash Course in Perl – Perl tutorial for C programmers

String ModifiersString Modifiers

\U – translate rest to uppercase\U – translate rest to uppercaseprint “My name is \Uinigo montoya!”;print “My name is \Uinigo montoya!”;My name is INIGO MONTOYA!My name is INIGO MONTOYA!

\L – translate rest to lowercase\L – translate rest to lowercaseprint “I LIKE /LLOWERCASE”;print “I LIKE /LLOWERCASE”;I LIKE lowercaseI LIKE lowercase

\\ - Backslash\\ - Backslash\n – Line feed\n – Line feed\r – Carriage return\r – Carriage return\E – Early terminator for \U, \L\E – Early terminator for \U, \L

Page 19: Crash Course in Perl – Perl tutorial for C programmers

ArraysArrays

• Variables are preceded by a @Variables are preceded by a @

• Ordered sets of scalarsOrdered sets of scalars

• Native support for array operationsNative support for array operations

• Examples:Examples:– @ar1 = (1, 2, 3);@ar1 = (1, 2, 3);– @arSet = (1..50, 99, 3);@arSet = (1..50, 99, 3);– @arMixed = ($x, 5, “even strings”);@arMixed = ($x, 5, “even strings”);– @hex = (“0” .. “9”, “a” .. “f”);@hex = (“0” .. “9”, “a” .. “f”);– @names = qw(Dan Naama Yael Marina);@names = qw(Dan Naama Yael Marina);

Page 20: Crash Course in Perl – Perl tutorial for C programmers

Using ArraysUsing Arrays

@x = (3, 1, 4);@x = (3, 1, 4);print @x; => 314print @x; => 314print “@x”; => 3 1 4print “@x”; => 3 1 4print $x[0]; => 3;print $x[0]; => 3;print $x[-1]; => 4;print $x[-1]; => 4;print “there are “ . scalar(@x) “ elements”;print “there are “ . scalar(@x) “ elements”;print “last element is $#x”; # scalar(@x)-1print “last element is $#x”; # scalar(@x)-1

$$x = @x; # same as scalar(@x)x = @x; # same as scalar(@x)These are still two different variables!These are still two different variables!Named @x, and $x.Named @x, and $x.

Page 21: Crash Course in Perl – Perl tutorial for C programmers

Array OperationsArray Operations

• push – push – add to tail of arrayadd to tail of array• pop – pop – remove last element of arrayremove last element of array• shift – shift – remove first element of arrayremove first element of array• unshift – unshift – add to head of arrayadd to head of array• delete $array[index] – delete $array[index] – remove by indexremove by index• splice – splice – replace elements inside arrayreplace elements inside array• sort – sort – sort array alphanumericallysort array alphanumerically• split – split – split string into arraysplit string into array

Page 22: Crash Course in Perl – Perl tutorial for C programmers

Array Operations – Push/PopArray Operations – Push/Pop

@@stack = (); # declare an empty arraystack = (); # declare an empty arraypush(@stack, 1); # (1)push(@stack, 1); # (1)push(@stack, 2 .. 5); # (1,2,3,4,5)push(@stack, 2 .. 5); # (1,2,3,4,5)print “Stack is @stack\n”;print “Stack is @stack\n”;Stack is 1 2 3 4 5Stack is 1 2 3 4 5

print “Last was “ . pop(@stack) . “\n”;print “Last was “ . pop(@stack) . “\n”;Last was 5Last was 5

Print “Stack is @stack\n”;Print “Stack is @stack\n”;Stack is 1 2 3 4Stack is 1 2 3 4

Page 23: Crash Course in Perl – Perl tutorial for C programmers

Array Operations – Shift/UnshiftArray Operations – Shift/Unshift

@list = (); # declare an empty list@list = (); # declare an empty listunshift(@list, 1); # (1)unshift(@list, 1); # (1)unshift(@list, (2, 3)); # (2, 3, 1)unshift(@list, (2, 3)); # (2, 3, 1)Print “List is @list\n”;Print “List is @list\n”;List is 2 3 1List is 2 3 1

Print “First was “ . Shift(@list) . “\n”;Print “First was “ . Shift(@list) . “\n”;First was 2First was 2

Print “List is @list\n”;Print “List is @list\n”;List is 3 1List is 3 1

Page 24: Crash Course in Perl – Perl tutorial for C programmers

Array Operations – SortArray Operations – Sort

@fruits = qw(Oranges Apples Bananas);@fruits = qw(Oranges Apples Bananas);

@sorted = sort(@fruits);@sorted = sort(@fruits);

print “I grow: @sorted\n”;print “I grow: @sorted\n”;

I growI grow: : Apples Bananas OrangesApples Bananas Oranges

Sort creates a new copy of array, and never Sort creates a new copy of array, and never

modifies input.modifies input.

Page 25: Crash Course in Perl – Perl tutorial for C programmers

Array Operations – Join/SplitArray Operations – Join/Split

@array = (“Apples”, “Bananas”, “Oranges”);@array = (“Apples”, “Bananas”, “Oranges”);print join(“\n”, @array); print join(“\n”, @array); ApplesApplesBananasBananasOrangesOranges

$csv = “50,10,20”;$csv = “50,10,20”;@elements = split(‘,’, $csv);@elements = split(‘,’, $csv);print “Elements: @elements\n”;print “Elements: @elements\n”;Elements: 50 10 20Elements: 50 10 20

Page 26: Crash Course in Perl – Perl tutorial for C programmers

Array Operations – SliceArray Operations – Slice

@values = (0, 1, 2, 3, 4, 5);@values = (0, 1, 2, 3, 4, 5);

@slice = @values[0, 3..5];@slice = @values[0, 3..5];

print “Slice is @slice\n”;print “Slice is @slice\n”;

0 3 4 50 3 4 5

@slice is a new array, @values is not affected@slice is a new array, @values is not affected

Page 27: Crash Course in Perl – Perl tutorial for C programmers

Array Operations – SpliceArray Operations – Splice

Syntax: Syntax: splice(@array, $start, $len, @new=())splice(@array, $start, $len, @new=())

@@values = (1, 2, 3, 4, 5);values = (1, 2, 3, 4, 5);@removed = splice(@values, 1, 3);@removed = splice(@values, 1, 3);print “Removed @removed, left with @values\n”;print “Removed @removed, left with @values\n”;Removed 2 3 4, left with 1 5Removed 2 3 4, left with 1 5

@values = (1, 2, 3, 4, 5);@values = (1, 2, 3, 4, 5);splice(@values, 1, 3, (“a”, “b”, “c”));splice(@values, 1, 3, (“a”, “b”, “c”));print “Spliced into @values\n”;print “Spliced into @values\n”;Spliced into 1 a b c 5Spliced into 1 a b c 5

Page 28: Crash Course in Perl – Perl tutorial for C programmers

HashesHashes

• Preceded by a %Preceded by a %• Unordered map between keys and valuesUnordered map between keys and values

%empty = ();%empty = ();%prices = (%prices = (

““Life of Brian” => “10.5”,Life of Brian” => “10.5”,Happiness => 12.2,Happiness => 12.2,

););

$prices{‘Holy Grail’} = 9.99;$prices{‘Holy Grail’} = 9.99;print $prices{‘Happiness’};print $prices{‘Happiness’};

Page 29: Crash Course in Perl – Perl tutorial for C programmers

Hashes OperationsHashes Operations

keys – returns keys of hash as an arraykeys – returns keys of hash as an array

values – returns values of hash as an arrayvalues – returns values of hash as an array

%hash = (“a” => “1”, “b” => “2”);%hash = (“a” => “1”, “b” => “2”);

print keys(%hash);print keys(%hash);

print values(%hash);print values(%hash);

Page 30: Crash Course in Perl – Perl tutorial for C programmers

Hash OperationsHash Operations

exists – returns true if key existsexists – returns true if key exists

delete – delete a key/value pairdelete – delete a key/value pair

%hash = (“apples” => 50, “oranges” => 20);%hash = (“apples” => 50, “oranges” => 20);

print exists($hash{‘apples’});print exists($hash{‘apples’});

11

delete $hash{‘oranges’};delete $hash{‘oranges’};

print keys(%hash);print keys(%hash);

applesapples

Page 31: Crash Course in Perl – Perl tutorial for C programmers

ConditionalsConditionals

Typical Typical if/elsif/elseif/elsif/else code block: code block:

ifif (($var1 > $var2$var1 > $var2) {) {

print “$var1 > $var2\n”;print “$var1 > $var2\n”;

}} elsifelsif (($var1 < $var2$var1 < $var2)) {{

print “$var1 < $var2\n”;print “$var1 < $var2\n”;

} else {} else {print “$var1 == $var2\n”;print “$var1 == $var2\n”;

}}

Page 32: Crash Course in Perl – Perl tutorial for C programmers

ConditionalsConditionals

$$x == $yx == $y$$x eq $yx eq $y

$$x != $yx != $y$$x ne $yx ne $y

$$x < $yx < $y$$x lt $yx lt $y

$$x > $yx > $y$$x gt $yx gt $y

$$x <= $yx <= $y$$x le $yx le $y

$$x >= $yx >= $y$$x ge $yx ge $y

$$expr1 && $expr2expr1 && $expr2$$expr1 and $expr2expr1 and $expr2

$$expr1 || $expr2expr1 || $expr2$$expr1 or $expr2expr1 or $expr2

$ !$ !exprexprnot $exprnot $expr

True is everything that is not false | False is everything that evaluates to zero ~ String comparisons must be done with text abbreviation (eq, ne)~

Page 33: Crash Course in Perl – Perl tutorial for C programmers

ConditionalsConditionals

NotesNotes• Expression must be enveloped with a normal brackets ( ).Expression must be enveloped with a normal brackets ( ).• After expression, else and elsif must follow a code block After expression, else and elsif must follow a code block

brackets { }.brackets { }.

A very uncomfortable situation, the simplest if takesA very uncomfortable situation, the simplest if takesseveral lines!!several lines!!

if ($a < $min) {if ($a < $min) {$a = $min;$a = $min;

}}

AH! YOU’RE IN LUCK!AH! YOU’RE IN LUCK!

Page 34: Crash Course in Perl – Perl tutorial for C programmers

Rerversed ConditionalsRerversed Conditionals

Unique reversed conditionals:Unique reversed conditionals:

Result precedes condition!Result precedes condition!

$a = $min $a = $min ifif $a > $min; $a > $min;

$a = $min $a = $min unlessunless $a < $min; $a < $min;

Page 35: Crash Course in Perl – Perl tutorial for C programmers

Sexy ConditionalsSexy Conditionals

If used correctly, Perl’s syntax is literal:If used correctly, Perl’s syntax is literal:

exit unless $pass eq “secret”;exit unless $pass eq “secret”;

Page 36: Crash Course in Perl – Perl tutorial for C programmers

More About ConditionalsMore About Conditionals

Perl uses Perl uses early-outearly-out expression evaluations expression evaluations

$val == 5 && print “It equals 5!”;$val == 5 && print “It equals 5!”;

$val < 0 && print “It’s negative!”;$val < 0 && print “It’s negative!”;

$val == 5 || print “Differs from 5!”;$val == 5 || print “Differs from 5!”;

$val < 0 || print “It’s positive!”;$val < 0 || print “It’s positive!”;

Page 37: Crash Course in Perl – Perl tutorial for C programmers

Last Two Notes About VariablesLast Two Notes About Variables

Reading undefined variables default to “”:Reading undefined variables default to “”:print $unknown_variable; # emptyprint $unknown_variable; # emptyprint $unknown_variable + 1; # 1print $unknown_variable + 1; # 1

$foo += 5;$foo += 5;print $foo; # 5print $foo; # 5

A simple typo can end up in hours of A simple typo can end up in hours of debugging. debugging. Luckily:Luckily:

Page 38: Crash Course in Perl – Perl tutorial for C programmers

Last Two Notes About VariablesLast Two Notes About Variables

Page 39: Crash Course in Perl – Perl tutorial for C programmers

use strictuse strict

• use strict;use strict; at the beginning of the perl at the beginning of the perl script.script.

• Declared variables with “Declared variables with “mymy”. Use of ”. Use of variable that wasn’t declared will result in variable that wasn’t declared will result in error.error.

use strict;use strict;my $name = “Johnny”;my $name = “Johnny”;

Page 40: Crash Course in Perl – Perl tutorial for C programmers

Two Last Notes About VariablesTwo Last Notes About Variables

You can determine in run time if a variable You can determine in run time if a variable

is defined or not:is defined or not:

print “yay!!\n” if defined $foo;print “yay!!\n” if defined $foo;

print “oh! oh!” unless defined $foo;print “oh! oh!” unless defined $foo;

Page 41: Crash Course in Perl – Perl tutorial for C programmers

Regular ExpressionsRegular Expressions

Perl has native RE support Perl has native RE support

If ($email =~ /^\w+@\w+\.\w+$/)If ($email =~ /^\w+@\w+\.\w+$/)

{{

print “Your email address is valid”;print “Your email address is valid”;

}}

Page 42: Crash Course in Perl – Perl tutorial for C programmers

Regular Expressions SyntaxRegular Expressions Syntax

Match with:Match with: $str =~ / expr / (modifiers);$str =~ / expr / (modifiers);

Replace with:Replace with: $str =~ s / expr / (with) / (mod);$str =~ s / expr / (with) / (mod);

Easier to learn by exampleEasier to learn by example

Page 43: Crash Course in Perl – Perl tutorial for C programmers

Matching With REMatching With RE

$$str = “I like coffee”;str = “I like coffee”;

if ($str =~ /I like if ($str =~ /I like (.+)(.+)/)/)

{{

print “He likes $1!!\n”;print “He likes $1!!\n”;

}}

He likes coffee!!He likes coffee!!

(Brackets) keep matched values in variables(Brackets) keep matched values in variables

$1 and onwards$1 and onwards

Page 44: Crash Course in Perl – Perl tutorial for C programmers

Replacing With REReplacing With RE

$str = “I like coffee”;$str = “I like coffee”;$str =~ s/coffee/Coca Cola/;$str =~ s/coffee/Coca Cola/;print $str;print $str;I like Coca ColaI like Coca Cola

$$str = “Einstein, Epstein, Levinstein”;str = “Einstein, Epstein, Levinstein”;$str =~ s/stein/vich/;$str =~ s/stein/vich/;print $str;print $str;Einvich, Epstein, LevinsteinEinvich, Epstein, Levinstein

$str =~ s/stein/vich/g;$str =~ s/stein/vich/g;Einvich, Epvich, LevinvichEinvich, Epvich, Levinvich

Use s/ to replace matches using regexp. Use modifier /gUse s/ to replace matches using regexp. Use modifier /gto replace all matches (not just the first).to replace all matches (not just the first).

Page 45: Crash Course in Perl – Perl tutorial for C programmers

Replacing with MatchesReplacing with Matches

$str = “John Smith”;$str = “John Smith”;

$str =~ s/(\w+) (\w+)/$2 $1/;$str =~ s/(\w+) (\w+)/$2 $1/;

print $str;print $str;

Smith JohnSmith John

Page 46: Crash Course in Perl – Perl tutorial for C programmers

RE ConditionalsRE Conditionals

Positive Matching:Positive Matching:

if ($name if ($name =~=~ /stein$/) /stein$/){{

print “Smarty!”;print “Smarty!”; }}

Negative Matching:Negative Matching:

if ($name if ($name !~!~ /stein$/) /stein$/) {{

print “Nope!”;print “Nope!”;}}

Page 47: Crash Course in Perl – Perl tutorial for C programmers

diedie!!

Damage control with die and warn. Die (with optional parameter), prints anDamage control with die and warn. Die (with optional parameter), prints anerror message and stops script execution. Warn prints warning message error message and stops script execution. Warn prints warning message but keeps running.but keeps running.

my $name = "Me";my $name = "Me";

$name eq "You" || die "Oh! I wasn't expecting $name!\n";$name eq "You" || die "Oh! I wasn't expecting $name!\n";

Oh! I wasn't expecting Me! at die.pl line 2Oh! I wasn't expecting Me! at die.pl line 2

------------------------------------------------------------------------------------------------------------------

my $age = 10;my $age = 10;

$age >= 21 || warn "You are not supposed to be drinking!";$age >= 21 || warn "You are not supposed to be drinking!";

print "Would you like cigarettes as well?\n";print "Would you like cigarettes as well?\n";

You are not supposed to be drinking! at warn.pl line 2.You are not supposed to be drinking! at warn.pl line 2.

Would you like cigarettes as well?Would you like cigarettes as well?

Page 48: Crash Course in Perl – Perl tutorial for C programmers

IterationsIterations

• Iteration by range ($start .. $end)Iteration by range ($start .. $end)• Iteration on arrayIteration on array• Traversing a hash (key/value pairs)Traversing a hash (key/value pairs)• While do / do whileWhile do / do while

Page 49: Crash Course in Perl – Perl tutorial for C programmers

Iterations by rangeIterations by range

Syntax:Syntax:for (<start_expr>; <end_condition>; <loop_expr>)for (<start_expr>; <end_condition>; <loop_expr>){{

# code# code}}

Example:Example:for (my $i=0; $i<100; $i++)for (my $i=0; $i<100; $i++){{

print “I: $i\n”;print “I: $i\n”;}}

# $i is not longer defined at this point# $i is not longer defined at this point

Page 50: Crash Course in Perl – Perl tutorial for C programmers

Iteration on ArrayIteration on Array

Syntax:Syntax:foreach <$iteration_variable> (<@loop_array>)foreach <$iteration_variable> (<@loop_array>){{

# code# code}}

Example:Example:@names = qw(Sarah John Terminator);@names = qw(Sarah John Terminator);foreach my $name (@names)foreach my $name (@names){{

print “I am $name\n”;print “I am $name\n”;}}

Page 51: Crash Course in Perl – Perl tutorial for C programmers

Iteration on ArrayIteration on Array

More examples:More examples:

# anonymous array# anonymous arrayfor $i (1,2,3,4,5,6,’boom’,8,9)for $i (1,2,3,4,5,6,’boom’,8,9){{

print “$i!\n”;print “$i!\n”;}}

----------- ----------- ----------- ----------- -------------------- ----------- ----------- ----------- ---------

# anonymous loop# anonymous loopfor (1..15)for (1..15){{

print “I will not talk in class\n”;print “I will not talk in class\n”;}}

Page 52: Crash Course in Perl – Perl tutorial for C programmers

Traversing a HashTraversing a Hash

# unsorted traverse on hash using each()# unsorted traverse on hash using each()my %ages = (Barney => 30, Fred => 45);my %ages = (Barney => 30, Fred => 45);while (($name, $age) = each(%ages))while (($name, $age) = each(%ages)){{

print “$name is $age years old\n”;print “$name is $age years old\n”;}}

OROR

# use keys() to control traverse order# use keys() to control traverse ordermy %ages = (Barney => 30, Fred => 45);my %ages = (Barney => 30, Fred => 45);foreach my $name (sort(keys(%ages)))foreach my $name (sort(keys(%ages))){{

print “$name is $ages{$name} years old\n”;print “$name is $ages{$name} years old\n”;}}

Page 53: Crash Course in Perl – Perl tutorial for C programmers

While do / do whileWhile do / do while

Completely identical to other programming languages:Completely identical to other programming languages:

my $i = 0;my $i = 0;

while ($i != 5)while ($i != 5)

{{

$i = int(rand(10));$i = int(rand(10));

print “Randomly picked: $i\n";print “Randomly picked: $i\n";

}}

While-do checks break-statement before executing codeWhile-do checks break-statement before executing code

block.block.

Page 54: Crash Course in Perl – Perl tutorial for C programmers

While do / do whileWhile do / do while

Completely identical to other programming languages:Completely identical to other programming languages:

my $i = 0;my $i = 0;dodo{{$i = int(rand(10));$i = int(rand(10));print “Randomly picked: $i\n";print “Randomly picked: $i\n";

} while ($i != 5);} while ($i != 5);

(why did we have to declare $i outside the while block?)(why did we have to declare $i outside the while block?)

Do-while executes block at least once. Do-while executes block at least once.

Page 55: Crash Course in Perl – Perl tutorial for C programmers

Next and LastNext and Last

Are C’s and Java’s ‘continue’ and ‘break’ (respectively)Are C’s and Java’s ‘continue’ and ‘break’ (respectively)

nextnext - skip to the next iteration- skip to the next iteration

lastlast - break current loop immediately- break current loop immediately

Page 56: Crash Course in Perl – Perl tutorial for C programmers

Next and LastNext and Last

ExamplesExamples::for for ((my $imy $i==0; $i<5; $i0; $i<5; $i++)++){{

next unless next unless (($i $i % % 2 2 == == 00));;print $i;print $i;

{{

Examples:Examples:@array = (10, 20, 30, 40, 50);@array = (10, 20, 30, 40, 50);for (my $i=0; $i<5; $i++)for (my $i=0; $i<5; $i++){{

last if $array[$i] > 30;last if $array[$i] > 30;print $i;print $i;

}}

Page 57: Crash Course in Perl – Perl tutorial for C programmers

Executing System CommandsExecuting System Commands

Perl supports both passthru and fetch-output modes of command linePerl supports both passthru and fetch-output modes of command lineexecutions.executions.

Use Use system() system() to run commands:to run commands:Examples:Examples:

system(“ifconfig eth0:1 down”);system(“ifconfig eth0:1 down”);system(“/bin/echo Network is now down!”);system(“/bin/echo Network is now down!”);system(“ls /tmp”);system(“ls /tmp”);

All output is merged with perl’s stdout. Errorlevel returned from lastAll output is merged with perl’s stdout. Errorlevel returned from lastsystem command executed is stored in a variable called $?. system command executed is stored in a variable called $?. Yes, that’sYes, that’s$?.$?.

Page 58: Crash Course in Perl – Perl tutorial for C programmers

Executing System CommandsExecuting System Commands` `

Backtick (`) fetches the output and passes it back as a single string.Backtick (`) fetches the output and passes it back as a single string.

my $text = `ls -1`;my $text = `ls -1`;foreach my $filename (sort(split(“\n”, $text)))foreach my $filename (sort(split(“\n”, $text))){{

print “Reading $filename..\n”;print “Reading $filename..\n”;}}

Reading backtick.pl..Reading backtick.pl..Reading bin..Reading bin..Reading eg..Reading eg..Reading etc..Reading etc..Reading html..Reading html..Reading lib..Reading lib..Reading site..Reading site..

Page 59: Crash Course in Perl – Perl tutorial for C programmers

FILESFILES

Files in Perl are handled similar to native C programs on Unix.Files in Perl are handled similar to native C programs on Unix.

All file handles must be declared in UPPERCASE (and no leading $, @All file handles must be declared in UPPERCASE (and no leading $, @or %).or %).

We will cover:We will cover:1.1. Opening and creating filesOpening and creating files2.2. Reading and writing to filesReading and writing to files3.3. Reading text lines from files (and chomp)Reading text lines from files (and chomp)4.4. Additional conditionals -XAdditional conditionals -X5.5. File operations (rename, copy, delete)File operations (rename, copy, delete)6.6. Finding filesFinding files7.7. Some useful packagesSome useful packages

Page 60: Crash Course in Perl – Perl tutorial for C programmers

Opening and Creating FilesOpening and Creating Files

Syntax:Syntax:open(FILEHANDLE, “filename+access-mode”);open(FILEHANDLE, “filename+access-mode”);

Access mode support:Access mode support:<< - read only- read only> > - write only (create and truncate existing file)- write only (create and truncate existing file)>>>> - append (write at the end of file, creates if doesn’t exist)- append (write at the end of file, creates if doesn’t exist)+<+< - read and write- read and write|| - pipe to another program (as input or output)- pipe to another program (as input or output)

Examples:Examples:open(FH, “<commands.txt”) || die “Failed opening file”;open(FH, “<commands.txt”) || die “Failed opening file”;open(FH, “ls –1|”);open(FH, “ls –1|”);open(FH, “>>debug.log”) || die “Failed to append file open(FH, “>>debug.log”) || die “Failed to append file debug.log”;debug.log”;

Page 61: Crash Course in Perl – Perl tutorial for C programmers

Closing FilesClosing Files

Perl automatically closes all files upon script termination.Perl automatically closes all files upon script termination.

Regardless, to force immediate release of resources, use:Regardless, to force immediate release of resources, use:

Syntax:Syntax:

close FH;close FH;

Page 62: Crash Course in Perl – Perl tutorial for C programmers

Reading from filesReading from files

Reading is done using <FILEHANDLE> syntax. The angle brackets are Reading is done using <FILEHANDLE> syntax. The angle brackets are part of the language!part of the language!

open(FH, “<commands.txt”) || die “can’t open!”;open(FH, “<commands.txt”) || die “can’t open!”;$first_line = <FH>;$first_line = <FH>;$second_line = <FH>;$second_line = <FH>;@rest_of_file = <FH>;@rest_of_file = <FH>;

If lvalue is scalar, perl will fetch one line. If lvalue is array, Perl will fetchIf lvalue is scalar, perl will fetch one line. If lvalue is array, Perl will fetchas much as it can (until eof). “print <FH>;” will print all contents. as much as it can (until eof). “print <FH>;” will print all contents.

Page 63: Crash Course in Perl – Perl tutorial for C programmers

Reading from FilesReading from Files

A typical iterator that runs through lines of a file looks like:A typical iterator that runs through lines of a file looks like:

open(FH, “<servers.lst”) || die “no server list!”;open(FH, “<servers.lst”) || die “no server list!”;while (my $line = <FH>)while (my $line = <FH>){{

print “Checking server $line..\n”;print “Checking server $line..\n”;}}close(FH);close(FH);

Checking server AChecking server A....Checking server BChecking server B....Checking server CChecking server C....

Oh oh! Perl loads the \n at the end of the line as well!!Oh oh! Perl loads the \n at the end of the line as well!!

Page 64: Crash Course in Perl – Perl tutorial for C programmers

Reading from Files – ChompReading from Files – Chomp!!

When Perl reads a file, it keeps the trailing \n at each line.When Perl reads a file, it keeps the trailing \n at each line.Introducing Chomp & Chop.Introducing Chomp & Chop.

Chop Chop removes the last character of any string.removes the last character of any string.

ChompChomp removes the trailing character if it’s a line separator (safer) removes the trailing character if it’s a line separator (safer)

open(FH, “<command.txt”) || die;open(FH, “<command.txt”) || die;$line = <FH>;$line = <FH>;chomp $line;chomp $line;print “Loaded $line from file!\n”;print “Loaded $line from file!\n”;

Page 65: Crash Course in Perl – Perl tutorial for C programmers

Reading from STDINReading from STDIN

Reading from stdin is done by either accessing a filehandle called “”Reading from stdin is done by either accessing a filehandle called “”(that’s empty filename) or one called STDIN.(that’s empty filename) or one called STDIN.

$line = <>;$line = <>; # will read one line from stdin# will read one line from stdin$line = <STDIN>; $line = <STDIN>; # identically# identically

In turn, looping on stdin (until eof) will probably lookIn turn, looping on stdin (until eof) will probably looklike this:like this:

while (my $str = <>)while (my $str = <>){{

chomp $str;chomp $str;print “Got $str”;print “Got $str”;

}}

Page 66: Crash Course in Perl – Perl tutorial for C programmers

Writing to FilesWriting to Files

Writing is done using normal print(). Print prints exactly what is passed,Writing is done using normal print(). Print prints exactly what is passed,and is binary safe (“\0” does not terminate string like in C).and is binary safe (“\0” does not terminate string like in C).

NOTE: print is a bit hacked when it comes to writing to files, it doesn’tNOTE: print is a bit hacked when it comes to writing to files, it doesn’tact like other functions.act like other functions.

open(FH, “>debuglog.txt”);open(FH, “>debuglog.txt”);print FH “This is the first line\n”;print FH “This is the first line\n”;# or# orprint(FH “This is the first line\n”);print(FH “This is the first line\n”);

Did you notice there’s no comma (,) after file handle?Did you notice there’s no comma (,) after file handle?

Page 67: Crash Course in Perl – Perl tutorial for C programmers

Additional Conditional -XAdditional Conditional -X

Perl follows shell script conventions and can determine file access Perl follows shell script conventions and can determine file access

if (-X “myfile”)if (-X “myfile”){{

# code# code}}

Operator –X can be any of these:Operator –X can be any of these:-r-r - file is readable by uid/gid- file is readable by uid/gid-w -w - file is writable by uid/gid- file is writable by uid/gid-x-x - file is executable by uid/gid- file is executable by uid/gid-f-f - file is a plain file- file is a plain file-d-d - file is a directory- file is a directory-e-e - file exists (same as –f || -d)- file exists (same as –f || -d)

Example:Example:-e “setup.tar.gz” || die “setup.tar.gz is missing!”;-e “setup.tar.gz” || die “setup.tar.gz is missing!”;

Page 68: Crash Course in Perl – Perl tutorial for C programmers

Renaming FilesRenaming Files

Use rename() to rename files, exactly as you would with mv in shell or Use rename() to rename files, exactly as you would with mv in shell or rename() in C.rename() in C.

Example:Example:rename(“oldcapture.cap”, “server1.cap”);rename(“oldcapture.cap”, “server1.cap”);

NOTE: rename() only works on the same partition. Otherwise, rename NOTE: rename() only works on the same partition. Otherwise, rename will fail. Wait for package File::Copy! will fail. Wait for package File::Copy!

Page 69: Crash Course in Perl – Perl tutorial for C programmers

Deleting FilesDeleting Files

Delete in Unix is termed “unlink”.Delete in Unix is termed “unlink”.

To remove a file, use unlink(filename).To remove a file, use unlink(filename).

Examples:Examples:unlink(“myfile”);unlink(“myfile”);unlink(“myfile”) || warn “could not delete myfile!”;unlink(“myfile”) || warn “could not delete myfile!”;

Page 70: Crash Course in Perl – Perl tutorial for C programmers

Finding FilesFinding Files

glob() matches all files and returns array of filenamesglob() matches all files and returns array of filenames

# match all *.cap files in root directory# match all *.cap files in root directory@captures = glob(“/captures/*.cap”);@captures = glob(“/captures/*.cap”);

# delete all files in the current directory# delete all files in the current directory@all_files = sort(glob(“*”));@all_files = sort(glob(“*”));foreach $file (@all_files)foreach $file (@all_files){{

# delete all files unconditionally!# delete all files unconditionally!unlink($file);unlink($file);

}}

Page 71: Crash Course in Perl – Perl tutorial for C programmers

Useful File Handling PackagesUseful File Handling Packages

Perl is bundled with these Core Modules. Perl is bundled with these Core Modules.

use FileHandle – object methods for filehandles (objectuse FileHandle – object methods for filehandles (objectoriented file access)oriented file access)

use File::Copy – copy and move files (even betweenuse File::Copy – copy and move files (even betweenpartitions)partitions)

use File::Compare – compare files and their contentsuse File::Compare – compare files and their contents

use File::Find – traverse directory treeuse File::Find – traverse directory tree

use File::Fetch – fetch file/url contents (supports file,use File::Fetch – fetch file/url contents (supports file,ftp and http)ftp and http)

Page 72: Crash Course in Perl – Perl tutorial for C programmers

A word about $_ andA word about $_ and_@ _@

Perl has a default scalar and default array that is assumed asPerl has a default scalar and default array that is assumed asargument, if an argument is missing.argument, if an argument is missing.

The default scalar is named $_ and the default array is named @_.The default scalar is named $_ and the default array is named @_.

Consider the following example, what does it do?Consider the following example, what does it do?

split(" ", "My name is Mud");split(" ", "My name is Mud");foreach(@_)foreach(@_){{

s/([a-z]+)/\U$1 /g;s/([a-z]+)/\U$1 /g;print;print;

}}

Page 73: Crash Course in Perl – Perl tutorial for C programmers

A word about $_ andA word about $_ and_@ _@

These two code blocks are identical:These two code blocks are identical:

split(" ", "My name is Mud");split(" ", "My name is Mud");foreach (@_)foreach (@_){{

s/([a-z]+)/\U$1 /g;s/([a-z]+)/\U$1 /g;print;print;

}}

------------------------------------------------------------------------------------------------

@_ =@_ = split(" ", "My name is Mud"); split(" ", "My name is Mud");foreach foreach $_ $_ (@_)(@_){{

$_ =~$_ =~ s/([a-z]+)/\U$1 /g; s/([a-z]+)/\U$1 /g;printprint $_ $_;;

}}

Page 74: Crash Course in Perl – Perl tutorial for C programmers

A word about $_ andA word about $_ and_@ _@

Most string processing functions also update @_ and $_ when they areMost string processing functions also update @_ and $_ when they aredone. Conditionals and iterators assume $_ if not argument passed.done. Conditionals and iterators assume $_ if not argument passed.

Note: Very rarely people “use English;”, which defines $ARG exactlyNote: Very rarely people “use English;”, which defines $ARG exactlylike $_;like $_;

Page 75: Crash Course in Perl – Perl tutorial for C programmers

More Predefined VariablesMore Predefined Variables

Most of Perl’s predefined variables are one character scalars, notMost of Perl’s predefined variables are one character scalars, notnecessarily alphabetic. There are about 40 of them, below is a list ofnecessarily alphabetic. There are about 40 of them, below is a list ofthe most common:the most common:

• $_$_ default scalardefault scalar• @_ @_ default arraydefault array• $1 .. $1 .. parsed regexpparsed regexp• $?$? child error (system and backtick)child error (system and backtick)• $!$! last error in human readable stringlast error in human readable string• $$$$ pid of the current programpid of the current program• $0$0 program nameprogram name• @ARGV@ARGV arguments passed to programarguments passed to program• %ENV%ENV unix environment as hashunix environment as hash

Page 76: Crash Course in Perl – Perl tutorial for C programmers

Functions (sub)Functions (sub)

Functions in perl are defined using the “sub” reserved keyword. Their Functions in perl are defined using the “sub” reserved keyword. Their argument count is optional, and as the rest of Perl, return type is notargument count is optional, and as the rest of Perl, return type is notdefined at all.defined at all.

A stripped down declaration is syntaxed like this:A stripped down declaration is syntaxed like this:

sub foosub foo{{}}

Foo can be called with any number of parameters, and can return (orFoo can be called with any number of parameters, and can return (ornot, dynamically) any values. Return is done with “return” as same asnot, dynamically) any values. Return is done with “return” as same asother languages.other languages.

Page 77: Crash Course in Perl – Perl tutorial for C programmers

Functions (sub)Functions (sub)

Returning values:Returning values:

sub foosub foo{{

my $i = int(rand(5)); my $i = int(rand(5));

return “string” if $i == 1;return “string” if $i == 1;return 2 if $i == 2;return 2 if $i == 2;return undef if $i == 3;return undef if $i == 3;return if $i == 4;return if $i == 4;# if $i == 5, it will return undef as well# if $i == 5, it will return undef as well

}}

Page 78: Crash Course in Perl – Perl tutorial for C programmers

Functions (sub)Functions (sub)

There are three ways to call to Perl subroutines:There are three ways to call to Perl subroutines:

1.1. foo();foo();2.2. &foo;&foo;3.3. foo;foo;

The first two expressions are the same (& would be the prefix of aThe first two expressions are the same (& would be the prefix of afunction, as $ is of a scalar).function, as $ is of a scalar).

Third expression is a bit different. It assumes that Third expression is a bit different. It assumes that foofoo was declared was declaredbefore before the current expression executes.the current expression executes.

Maybe it’s more understandable with an example:Maybe it’s more understandable with an example:

Page 79: Crash Course in Perl – Perl tutorial for C programmers

Functions (sub)Functions (sub)

sub foosub foo

{{

return “works!”;return “works!”;

}}

# all of these work# all of these work

print &foo;print &foo;

print foo;print foo;

print foo();print foo();

# only this works ..# only this works ..

print foo();print foo();

print &foo;print &foo;

sub foosub foo

{{

return “works!”;return “works!”;

}}

This examples why both of these work fine:

exit unless defined $password;

exit() unless defined $password;

Page 80: Crash Course in Perl – Perl tutorial for C programmers

Passing argumentsPassing arguments

sub foosub foo{{

my $first_param = shift @_;my $first_param = shift @_;my $second_param = shift;my $second_param = shift;my ($third_param, $fourth_param) = @_;my ($third_param, $fourth_param) = @_;my (@rest) = @_;my (@rest) = @_;

print "$first_param";print "$first_param";print "$second_param";print "$second_param";print "$third_param";print "$third_param";print "$fourth_param";print "$fourth_param";print "@rest";print "@rest";

}}

foo(1, 2, 3, 4, 5, 6, 7, 8);foo(1, 2, 3, 4, 5, 6, 7, 8);

What will this program print?What will this program print?

Page 81: Crash Course in Perl – Perl tutorial for C programmers

Passing argumentsPassing arguments

112233443 4 5 6 7 83 4 5 6 7 8

Page 82: Crash Course in Perl – Perl tutorial for C programmers

Passing argumentsPassing arguments

While Perl can’t let you control what is passed, it DOES let you specifyWhile Perl can’t let you control what is passed, it DOES let you specifyhow many parameters are allowed in. Use $ as the number ofhow many parameters are allowed in. Use $ as the number ofacceptable arguments.acceptable arguments.

sub no_parameters()sub no_parameters(){{}}

sub one_parameter($)sub one_parameter($){{}}

sub three_parameters($$$)sub three_parameters($$$){{}}

Page 83: Crash Course in Perl – Perl tutorial for C programmers

Passing argumentsPassing arguments

Use @ in parameter list to accept array of zero or more parameters.Use @ in parameter list to accept array of zero or more parameters.Note that all parameters are merged into ONE @_ list.Note that all parameters are merged into ONE @_ list.

sub foo(@)sub foo(@){ {

print “@_”;print “@_”;}}

foo(“1”, “2”, qw(a b c));foo(“1”, “2”, qw(a b c));foo();foo();

Page 84: Crash Course in Perl – Perl tutorial for C programmers

Passing argumentsPassing arguments

Shift or array copy return Shift or array copy return undefundef if data is missing. if data is missing.

@names = qw(OnlyOneName);@names = qw(OnlyOneName);shift @names;shift @names;shift @names || die “there was only one name!”;shift @names || die “there was only one name!”;

Same principle is used a lot in Perl code:Same principle is used a lot in Perl code:

sub foo(@)sub foo(@){{

my $param1 = shift || return false;my $param1 = shift || return false;my $param2 = shift || return false;my $param2 = shift || return false;

}}

There is no need to check for defined/undefined if usingThere is no need to check for defined/undefined if using$. Perl will print an error if not enough arguments were$. Perl will print an error if not enough arguments werepassed in function call.passed in function call.

Page 85: Crash Course in Perl – Perl tutorial for C programmers

Passing hashesPassing hashes

sub processsub process{{

my $statname = shift || return;my $statname = shift || return;my %stats = @_;my %stats = @_;

while ((my $key, my $value) = each(%stats))while ((my $key, my $value) = each(%stats)){{

print “$statname: $key => $value\n”;print “$statname: $key => $value\n”;}}

}}

my %stats = (“fred” => 12, “barney” => 15);my %stats = (“fred” => 12, “barney” => 15);process(“uptime”, %stats);process(“uptime”, %stats);

Note: Remember! Don’t use scalars after array or hash (they will beNote: Remember! Don’t use scalars after array or hash (they will bemerged to that array)merged to that array)

Page 86: Crash Course in Perl – Perl tutorial for C programmers

PointersPointers

Please use them as little as possible, and only when needed.Please use them as little as possible, and only when needed.

Pointers are scalars ($) that refer to any other primitive. ToPointers are scalars ($) that refer to any other primitive. To

create a pointer to a variable, add a backslash (\) beforecreate a pointer to a variable, add a backslash (\) before

the variable like:the variable like:

$ref = \$value;$ref = \$value;

shuffle_array(\@my_array);shuffle_array(\@my_array);

SetCallback(\&my_callback);SetCallback(\&my_callback);

Page 87: Crash Course in Perl – Perl tutorial for C programmers

PointersPointers

Access referenced value by typecasting to the correct type:Access referenced value by typecasting to the correct type:

my my $$value = 1;value = 1;

my my $$ref = \$value;ref = \$value;

print “My reference is: $ref\n”;print “My reference is: $ref\n”;

print “But my real value is $$ref\n”;print “But my real value is $$ref\n”;

My reference is: SCALAR(0x22a0ac)My reference is: SCALAR(0x22a0ac)

But my real value is 1But my real value is 1

Page 88: Crash Course in Perl – Perl tutorial for C programmers

PointersPointers

Writing an inline sort using references:Writing an inline sort using references:

sub sort_array($)sub sort_array($)}}

my $ref = shift;my $ref = shift;@$ref = sort(@$ref);@$ref = sort(@$ref);

}}

my @array = (5,1,4,2,3);my @array = (5,1,4,2,3);sort_array(\@array);sort_array(\@array);print "@array\n";print "@array\n";

Page 89: Crash Course in Perl – Perl tutorial for C programmers

When to use pointersWhen to use pointers??

Pointers are evil, because they require the sub using it toPointers are evil, because they require the sub using it to

know it’s reference (unlike C++’s & and Java)know it’s reference (unlike C++’s & and Java)

So, when should you use pointers?So, when should you use pointers?

1.1. In a function, to change values of referenced variable.In a function, to change values of referenced variable.

2.2. Array of arrays / Hash of hashes.Array of arrays / Hash of hashes.

3.3. When mixing more than 1 array/hash in function call.When mixing more than 1 array/hash in function call.

4.4. When you simply want to make it unmaintainable :)When you simply want to make it unmaintainable :)

Page 90: Crash Course in Perl – Perl tutorial for C programmers

Hash DereferenceHash Dereference

Alternatively to hashes, and pointers to Alternatively to hashes, and pointers to

hash, you can use hash derefence. Scalarhash, you can use hash derefence. Scalar

for a hash!for a hash!

$stuff = ();$stuff = ();

$stuff->{‘items’} = 50;$stuff->{‘items’} = 50;

$stuff->{‘locations’} = 1;$stuff->{‘locations’} = 1;

UpdateStuff($stuff);UpdateStuff($stuff); # look ma, no pointers!# look ma, no pointers!

Page 91: Crash Course in Perl – Perl tutorial for C programmers

Hash DerefenceHash Derefence

sub updateStuff($)sub updateStuff($)

{{

my $ref = shift;my $ref = shift;

--$ref->{‘items’} || die “Out of items!”;--$ref->{‘items’} || die “Out of items!”;

}}

No typecasting needed. But no way to make items mutableNo typecasting needed. But no way to make items mutable

either.either.

Page 92: Crash Course in Perl – Perl tutorial for C programmers

Using Hash Core Subs withUsing Hash Core Subs with$ $

$$stuff stuff = ()= ();;$$stuffstuff-->{'items'} >{'items'} = = 4;4;$$stuffstuff-->{'locations'} >{'locations'} = = 1;1;

foreach my $key foreach my $key ((keyskeys(%(%$stuff$stuff)))){{print $key print $key . ": " . . ": " . $stuff$stuff-->{$key} >{$key} . ". "\n\n"";;

}}

locations: 1locations: 1items: 4items: 4

Page 93: Crash Course in Perl – Perl tutorial for C programmers

Perl PackagesPerl Packages

Denoted with .pm extension and with Denoted with .pm extension and with package package pragma.pragma.

Packages don’t necessarily mean object orientation. They are simply a Packages don’t necessarily mean object orientation. They are simply a way of organizing code.way of organizing code.

package VocalTec;package VocalTec;

sub banner()sub banner(){{

print “The first and best in IP telephony\n”;print “The first and best in IP telephony\n”;}}

1;1;

Packages must return a positive value. Hence the dummy Packages must return a positive value. Hence the dummy expression ‘1’ at the end.expression ‘1’ at the end.

Page 94: Crash Course in Perl – Perl tutorial for C programmers

Perl PackagesPerl Packages

Packages must be saved in files after their package name.Packages must be saved in files after their package name.For example:For example:

package VocalTec;package VocalTec;

Must be defined in Must be defined in VocalTec.pmVocalTec.pm

And can also be nested, for example:And can also be nested, for example:

package VocalTec::Devices::Gateway;package VocalTec::Devices::Gateway;

Must be defined in Must be defined in VocalTec/Devices/Gateway.pmVocalTec/Devices/Gateway.pm

Page 95: Crash Course in Perl – Perl tutorial for C programmers

Perl PackagesPerl Packages

Calling a function defined in a different packages is done by providingCalling a function defined in a different packages is done by providingfull path to it.full path to it.

use VocalTec;use VocalTec;

print VocalTec::getVersion();print VocalTec::getVersion();

Packages are only loaded to memory once, and only upon invocation Packages are only loaded to memory once, and only upon invocation ofof

‘‘use’.use’.

Page 96: Crash Course in Perl – Perl tutorial for C programmers

Perl PackagesPerl Packages

Core modules are located under C:\Perl\Lib

Page 97: Crash Course in Perl – Perl tutorial for C programmers

OOPOOP

Perl supports all attributes of a classic object Perl supports all attributes of a classic object oriented programming scheme.oriented programming scheme.

• InheritanceInheritance• EncapsulationEncapsulation• PolymorphismPolymorphism

……. All done by chance. All done by chance

Page 98: Crash Course in Perl – Perl tutorial for C programmers

OOP: BlessOOP: Bless

Let’s define our first class, Let’s define our first class, Animal, Animal, using the keyword ‘bless’. Sub new using the keyword ‘bless’. Sub new (convention) should allocate a hash, and bless it with the class name. This (convention) should allocate a hash, and bless it with the class name. This is how you create a new instance.is how you create a new instance.

package Animal;package Animal;

sub newsub new{{

my ($class) = @_;my ($class) = @_;

my $self = {};my $self = {};bless $self, $class;bless $self, $class;

return $self;return $self;}}

Page 99: Crash Course in Perl – Perl tutorial for C programmers

Keeping Data In InstanceKeeping Data In Instance

package Animal;package Animal;

sub newsub new

{{

my ($class) = @_;my ($class) = @_;

my $self = {};my $self = {};

$self->{'legs'} = 4;$self->{'legs'} = 4;

bless $self, $class;bless $self, $class;

return $self;return $self;

}}

Page 100: Crash Course in Perl – Perl tutorial for C programmers

Accessing ‘thisAccessing ‘this’’

‘‘this’, ‘self’ and ‘parent’ are not defined in Perl. Whenthis’, ‘self’ and ‘parent’ are not defined in Perl. Whencalling a sub by instance, the first variable in @_, is the calling a sub by instance, the first variable in @_, is the instance (that hash table from ‘new’.)instance (that hash table from ‘new’.)

sub legsCountsub legsCount{{

my ($self) = @_;my ($self) = @_;

return $self->{'legs'};return $self->{'legs'};}}

$my_cat = Animal->new();$my_cat = Animal->new();print $my_cat->legsCount();print $my_cat->legsCount();

Page 101: Crash Course in Perl – Perl tutorial for C programmers

InheritanceInheritance

Inheritance is defined entirely by @ISA variable, and Inheritance is defined entirely by @ISA variable, and SUPER constant.SUPER constant.

package Animal::Worm;package Animal::Worm;

use Animal;use Animal;use strict;use strict;our @ISA = qw(Animal);our @ISA = qw(Animal);

sub newsub new{{

my ($class) = shift;my ($class) = shift;

## my $self = $class->SUPER::new(@_);my $self = $class->SUPER::new(@_);my $self = Animal->new(@_);my $self = Animal->new(@_);bless $self, $class;bless $self, $class;

return $self;return $self;}}

Page 102: Crash Course in Perl – Perl tutorial for C programmers

PolymorphismPolymorphism

Polymorphism (Method Overloading) is changing aPolymorphism (Method Overloading) is changing asub behavior, doing something different than its SUPER. In Perl,sub behavior, doing something different than its SUPER. In Perl,all subs are virtual.all subs are virtual.

package Animal::Worm;package Animal::Worm;sub legsCountsub legsCount{{

my $self = shift;my $self = shift;

print “debug: returning leg count”;print “debug: returning leg count”; return $self->{‘legs’};return $self->{‘legs’};}}

Page 103: Crash Course in Perl – Perl tutorial for C programmers

PolymorphismPolymorphism

Method can call parent implementation atMethod can call parent implementation atwill (not instead).will (not instead).

sub fetchRandomRowsub fetchRandomRow{{

my $self = shift;my $self = shift;

if (int(rand(2)) == 0)if (int(rand(2)) == 0){{

return $self->SUPER::fetchRandomRow();return $self->SUPER::fetchRandomRow();}}elseelse{{

return int(rand($self->{‘number_of_rows’}));return int(rand($self->{‘number_of_rows’}));}}

}}

Page 104: Crash Course in Perl – Perl tutorial for C programmers

Use Switch / Feature ‘switch’Use Switch / Feature ‘switch’

use Switch; use Switch;

switch ($val) switch ($val) { {

case 1 { print "number 1" } case 1 { print "number 1" } case "a" { print "string a" } case "a" { print "string a" } case [1..10,42] { print "number in list" }case [1..10,42] { print "number in list" }case (@array) { print "number in list" }case (@array) { print "number in list" }case /\w+/ { print "pattern" } case /\w+/ { print "pattern" } case qr/\w+/ { print "pattern" } case qr/\w+/ { print "pattern" } case (%hash) { print "entry in hash" } case (%hash) { print "entry in hash" } case (\%hash) { print "entry in hash" } case (\%hash) { print "entry in hash" } case (\&sub) { print "arg to subroutine" }case (\&sub) { print "arg to subroutine" }else { print "previous case not true" }else { print "previous case not true" }

} }

Page 105: Crash Course in Perl – Perl tutorial for C programmers

Use ConstantUse Constant

use constant BUFFER_SIZE => 4096;use constant BUFFER_SIZE => 4096;

use constant PI => 4 * atan2 1,1;use constant PI => 4 * atan2 1,1;

print PI / 180.0;print PI / 180.0;

Page 106: Crash Course in Perl – Perl tutorial for C programmers

Best PracticeBest Practice

Set default value, unless specified otherwise:Set default value, unless specified otherwise:

$wait_seconds = 5 unless defined $wait_seconds; $wait_seconds = 5 unless defined $wait_seconds;

$max_files = shift || 10;$max_files = shift || 10;

Page 107: Crash Course in Perl – Perl tutorial for C programmers

Best PracticeBest Practice

Always Always use strictuse strict!!

Hey, better safe than sorry, right? :) Hey, better safe than sorry, right? :)

use strict;use strict;my $v = ‘this is a scalar!’;my $v = ‘this is a scalar!’;

Page 108: Crash Course in Perl – Perl tutorial for C programmers

Best PracticeBest Practice

Scripts grow faster than other programming codeScripts grow faster than other programming code

1. People tend to /just/ copy-paste subs into new scripts1. People tend to /just/ copy-paste subs into new scripts

2. Optimization is often overlooked, causing huge codebase as 2. Optimization is often overlooked, causing huge codebase as wellwell

3. Namespace mess3. Namespace mess

Create packages if you need the same sub twice!Create packages if you need the same sub twice!

Create subs with mutable variables (always return new copies ofCreate subs with mutable variables (always return new copies ofupdated variables)updated variables)

Page 109: Crash Course in Perl – Perl tutorial for C programmers

Think in CThink in C!!

In case you are writing a script with entryIn case you are writing a script with entrypoint (not a package,) write a main() sub!point (not a package,) write a main() sub!

sub main()sub main(){{

# my code begins here.# my code begins here.}}

main();main();

Page 110: Crash Course in Perl – Perl tutorial for C programmers

Best PracticeBest Practice

CPAN is there for you! Use it!CPAN is there for you! Use it!

If you thought of it, most chances If you thought of it, most chances somebody already implemented itsomebody already implemented it

http://www.cpan.org/modules/http://www.cpan.org/modules/

Page 111: Crash Course in Perl – Perl tutorial for C programmers

QuestionsQuestions??

Email me! Email me! [email protected]@megidish.net