PERLPERL
Pathologically Eclectic RubbishPathologically Eclectic Rubbish
ListerLister
PerlPerl
• Created by Larry WallCreated by Larry Wall
in 1987in 1987
• Latest version isLatest version is
5.10.0, released...
How It LooksHow It Looks
##!/!/usrusr//binbin//perlperl
$;="@{'`|;{'^'!.|-'}";$.++;$.++;$.++;$_="(.)?";/((?{$_.=$_}).)+$/;...
What’s So Special About It?What’s So Special About It?
• 20 years of stability. Has been in production20 years of stabilit...
Why You Should Use ItWhy You Should Use It
• Speed of DevelopmentSpeed of Development
– Large codebase publicly availableL...
Why You Should Use ItWhy You Should Use It
• Powerful string processingPowerful string processing
• Wide selection of edit...
ConvincedConvinced??
Course OutlineCourse Outline
• CodeflowCodeflow
• VariablesVariables
• ConditionalsConditionals
• Sexegers (regular expres...
Course Outline IICourse Outline II
• Using PackagesUsing Packages
• OOP in PerlOOP in Perl
• Best PracticesBest Practices
...
CodeflowCodeflow
• Perl is an interpreter and executesPerl is an interpreter and executes
statements in the order it reads...
Your First Perl ProgramYour First Perl Program
Get Yourself Some PerlGet Yourself Some Perl
• Two flavors of Perl are available forTwo flavors of Perl are available for
...
The BasicsThe Basics
$name = “Gil”;$name = “Gil”;
print “my name is $name!n”;print “my name is $name!n”;
my name is Gilmy ...
VariablesVariables
There are 5 data types in Perl:There are 5 data types in Perl:
1.1. ScalarScalar
2.2. ArrayArray
3.3. H...
ScalarsScalars
• Variables are preceded by $Variables are preceded by $
• Scalars are single, linear values. For example:S...
Scalar OperationsScalar Operations
$x = 3.0;$x = 3.0;
$y = 5;$y = 5;
print $x + $y; # addprint $x + $y; # add
print $x - $...
Scalar StringsScalar Strings
Use dot (.) to concatenate stringsUse dot (.) to concatenate strings
$str = “hello “ . $name ...
String ModifiersString Modifiers
U – translate rest to uppercaseU – translate rest to uppercase
print “My name is Uinigo m...
ArraysArrays
• Variables are preceded by a @Variables are preceded by a @
• Ordered sets of scalarsOrdered sets of scalars...
Using ArraysUsing Arrays
@x = (3, 1, 4);@x = (3, 1, 4);
print @x; => 314print @x; => 314
print “@x”; => 3 1 4print “@x”; =...
Array OperationsArray Operations
• push –push – add to tail of arrayadd to tail of array
• pop –pop – remove last element ...
Array Operations – Push/PopArray Operations – Push/Pop
@@stack = (); # declare an empty arraystack = (); # declare an empt...
Array Operations – Shift/UnshiftArray Operations – Shift/Unshift
@list = (); # declare an empty list@list = (); # declare ...
Array Operations – SortArray Operations – Sort
@fruits = qw(Oranges Apples Bananas);@fruits = qw(Oranges Apples Bananas);
...
Array Operations – Join/SplitArray Operations – Join/Split
@array = (“Apples”, “Bananas”, “Oranges”);@array = (“Apples”, “...
Array Operations – SliceArray Operations – Slice
@values = (0, 1, 2, 3, 4, 5);@values = (0, 1, 2, 3, 4, 5);
@slice = @valu...
Array Operations – SpliceArray Operations – Splice
Syntax:Syntax: splice(@array, $start, $len, @new=())splice(@array, $sta...
HashesHashes
• Preceded by a %Preceded by a %
• Unordered map between keys and valuesUnordered map between keys and values...
Hashes OperationsHashes Operations
keys – returns keys of hash as an arraykeys – returns keys of hash as an array
values –...
Hash OperationsHash Operations
exists – returns true if key existsexists – returns true if key exists
delete – delete a ke...
ConditionalsConditionals
TypicalTypical if/elsif/elseif/elsif/else code block:code block:
ifif (($var1 > $var2$var1 > $var...
ConditionalsConditionals
$$x == $yx == $y $$x eq $yx eq $y
$$x != $yx != $y $$x ne $yx ne $y
$$x < $yx < $y $$x lt $yx lt ...
ConditionalsConditionals
NotesNotes
• Expression must be enveloped with a normal brackets ( (.Expression must be enveloped...
Rerversed ConditionalsRerversed Conditionals
Unique reversed conditionals:Unique reversed conditionals:
Result precedes co...
Sexy ConditionalsSexy Conditionals
If used correctly, Perl’s syntax is literal:If used correctly, Perl’s syntax is literal...
More About ConditionalsMore About Conditionals
Perl usesPerl uses early-outearly-out expression evaluationsexpression eval...
Last Two Notes About VariablesLast Two Notes About Variables
Reading undefined variables default to “”:Reading undefined v...
Last Two Notes About VariablesLast Two Notes About Variables
use strictuse strict
• use strict;use strict; at the beginning of the perlat the beginning of the perl
script.script.
• De...
Two Last Notes About VariablesTwo Last Notes About Variables
You can determine in run time if a variableYou can determine ...
Regular ExpressionsRegular Expressions
Perl has native RE supportPerl has native RE support
If ($email =~ /^w+@w+.w+$/)If ...
Regular Expressions SyntaxRegular Expressions Syntax
Match with:Match with:
$str =~ / expr / (modifiers);$str =~ / expr / ...
Matching With REMatching With RE
$$str = “I like coffee”;str = “I like coffee”;
if ($str =~ /I likeif ($str =~ /I like (.+...
Replacing With REReplacing With RE
$str = “I like coffee”;$str = “I like coffee”;
$str =~ s/coffee/Coca Cola/;$str =~ s/co...
Replacing with MatchesReplacing with Matches
$str = “John Smith”;$str = “John Smith”;
$str =~ s/(w+) (w+)/$2 $1/;$str =~ s...
RE ConditionalsRE Conditionals
Positive Matching:Positive Matching:
if ($nameif ($name =~=~ /stein$/(/stein$/(
{{
print “S...
diedie!!
Damage control with die and warn. Die (with optional parameter(, prints anDamage control with die and warn. Die (...
IterationsIterations
• Iteration by range ($start .. $end(Iteration by range ($start .. $end(
• Iteration on arrayIteratio...
Iterations by rangeIterations by range
Syntax:Syntax:
for (<start_expr>; <end_condition>; <loop_expr>)for (<start_expr>; <...
Iteration on ArrayIteration on Array
Syntax:Syntax:
foreach <$iteration_variable> (<@loop_array>)foreach <$iteration_varia...
Iteration on ArrayIteration on Array
More examples:More examples:
# anonymous array# anonymous array
for $i (1,2,3,4,5,6,’...
Traversing a HashTraversing a Hash
# unsorted traverse on hash using each()# unsorted traverse on hash using each()
my %ag...
While do / do whileWhile do / do while
Completely identical to other programming languages:Completely identical to other p...
While do / do whileWhile do / do while
Completely identical to other programming languages:Completely identical to other p...
Next and LastNext and Last
Are C’s and Java’s ‘continue’ and ‘break’ (respectively(Are C’s and Java’s ‘continue’ and ‘brea...
Next and LastNext and Last
ExamplesExamples::
forfor ((my $imy $i==0; $i<5; $i0; $i<5; $i++)++)
{{
next unlessnext unless ...
Executing System CommandsExecuting System Commands
Perl supports both passthru and fetch-output modes of command linePerl ...
Executing System CommandsExecuting System Commands``
Backtick (`) fetches the output and passes it back as a single string...
FILESFILES
Files in Perl are handled similar to native C programs on Unix.Files in Perl are handled similar to native C pr...
Opening and Creating FilesOpening and Creating Files
Syntax:Syntax:
open(FILEHANDLE, “filename+access-mode”);open(FILEHAND...
Closing FilesClosing Files
Perl automatically closes all files upon script termination.Perl automatically closes all files...
Reading from filesReading from files
Reading is done using <FILEHANDLE> syntax. The angle brackets areReading is done usin...
Reading from FilesReading from Files
A typical iterator that runs through lines of a file looks like:A typical iterator th...
Reading from Files – ChompReading from Files – Chomp!!
When Perl reads a file, it keeps the trailing n at each line.When P...
Reading from STDINReading from STDIN
Reading from stdin is done by either accessing a filehandle called “”Reading from std...
Writing to FilesWriting to Files
Writing is done using normal print(). Print prints exactly what is passed,Writing is done...
Additional Conditional -XAdditional Conditional -X
Perl follows shell script conventions and can determine file accessPerl...
Renaming FilesRenaming Files
Use rename() to rename files, exactly as you would with mv in shell orUse rename() to rename ...
Deleting FilesDeleting Files
Delete in Unix is termed “unlink”.Delete in Unix is termed “unlink”.
To remove a file, use un...
Finding FilesFinding Files
glob() matches all files and returns array of filenamesglob() matches all files and returns arr...
Useful File Handling PackagesUseful File Handling Packages
Perl is bundled with these Core Modules.Perl is bundled with th...
A word about $_ andA word about $_ and@_@_
Perl has a default scalar and default array that is assumed asPerl has a defaul...
A word about $_ andA word about $_ and@_@_
These two code blocks are identical:These two code blocks are identical:
split(...
A word about $_ andA word about $_ and@_@_
Most string processing functions also update @_ and $_ when they areMost string...
More Predefined VariablesMore Predefined Variables
Most of Perl’s predefined variables are one character scalars, notMost ...
Functions (subFunctions (sub))
Functions in perl are defined using the “sub” reserved keyword. TheirFunctions in perl are ...
Functions (subFunctions (sub))
Returning values:Returning values:
sub foosub foo
{{
my $i = int(rand(5));my $i = int(rand(...
Functions (subFunctions (sub))
There are three ways to call to Perl subroutines:There are three ways to call to Perl subro...
Functions (subFunctions (sub))
sub foosub foo
{{
return “works!”;return “works!”;
}}
# all of these work# all of these wor...
Passing argumentsPassing arguments
sub foosub foo
{{
my $first_param = shift @_;my $first_param = shift @_;
my $second_par...
Passing argumentsPassing arguments
11
22
33
44
3 4 5 6 7 83 4 5 6 7 8
Passing argumentsPassing arguments
While Perl can’t let you control what is passed, it DOES let you specifyWhile Perl can’...
Passing argumentsPassing arguments
Use @ in parameter list to accept array of zero or more parameters.Use @ in parameter l...
Passing argumentsPassing arguments
Shift or array copy returnShift or array copy return undefundef if data is missing.if d...
Passing hashesPassing hashes
sub processsub process
{{
my $statname = shift || return;my $statname = shift || return;
my %...
PointersPointers
Please use them as little as possible, and only when needed.Please use them as little as possible, and on...
PointersPointers
Access referenced value by typecasting to the correct type:Access referenced value by typecasting to the ...
PointersPointers
Writing an inline sort using references:Writing an inline sort using references:
sub sort_array($)sub sor...
When to use pointersWhen to use pointers??
Pointers are evil, because they require the sub using it toPointers are evil, b...
Hash DereferenceHash Dereference
Alternatively to hashes, and pointers toAlternatively to hashes, and pointers to
hash, yo...
Hash DerefenceHash Derefence
sub updateStuff($)sub updateStuff($)
{{
my $ref = shift;my $ref = shift;
--$ref->{‘items’} ||...
Using Hash Core Subs withUsing Hash Core Subs with$$
$$stuffstuff = ()= ();;
$$stuffstuff-->{'items'}>{'items'} == 4;4;
$$...
Perl PackagesPerl Packages
Denoted with .pm extension and withDenoted with .pm extension and with packagepackage pragma.pr...
Perl PackagesPerl Packages
Packages must be saved in files after their package name.Packages must be saved in files after ...
Perl PackagesPerl Packages
Calling a function defined in a different packages is done by providingCalling a function defin...
Perl PackagesPerl Packages
Core modules are located under C:PerlLib
OOPOOP
Perl supports all attributes of a classic objectPerl supports all attributes of a classic object
oriented programmi...
OOP: BlessOOP: Bless
Let’s define our first class,Let’s define our first class, Animal,Animal, using the keyword ‘bless’. ...
Keeping Data In InstanceKeeping Data In Instance
package Animal;package Animal;
sub newsub new
{{
my ($class) = @_;my ($cl...
Accessing ‘thisAccessing ‘this’’
‘‘this’, ‘self’ and ‘parent’ are not defined in Perl. Whenthis’, ‘self’ and ‘parent’ are ...
InheritanceInheritance
Inheritance is defined entirely by @ISA variable, andInheritance is defined entirely by @ISA variab...
PolymorphismPolymorphism
Polymorphism (Method Overloading) is changing aPolymorphism (Method Overloading) is changing a
su...
PolymorphismPolymorphism
Method can call parent implementation atMethod can call parent implementation at
will (not instea...
Use Switch / Feature ‘switch’Use Switch / Feature ‘switch’
use Switch;use Switch;
switch ($val)switch ($val)
{{
case 1 { p...
Use ConstantUse Constant
use constant BUFFER_SIZE => 4096;use constant BUFFER_SIZE => 4096;
use constant PI => 4 * atan2 1...
Best PracticeBest Practice
Set default value, unless specified otherwise:Set default value, unless specified otherwise:
$w...
Best PracticeBest Practice
AlwaysAlways use strictuse strict!!
Hey, better safe than sorry, right? :)Hey, better safe than...
Best PracticeBest Practice
Scripts grow faster than other programming codeScripts grow faster than other programming code
...
Think in CThink in C!!
In case you are writing a script with entryIn case you are writing a script with entry
point (not a...
Best PracticeBest Practice
CPAN is there for you! Use it!CPAN is there for you! Use it!
If you thought of it, most chances...
QuestionsQuestions??
Email me!Email me! gil@megidish.netgil@megidish.net 
Upcoming SlideShare
Loading in …5
×

Crash Course in Perl – Perl tutorial for C programmers

6,684 views

Published on

Published in: Technology
  • @ChunBai I am so glad to hear. I made this for a company who just inherited a huge load of perl code and nobody in the company knew how to work with it. This presentation is a great overview and reference.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • this ppt is very usful, it helped me to refresh my Perl knowledge very quickly. I dive into those Perl script for work, the next day!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • @neerjapancholi glad you found this! I wrote this several years ago, for teaching a company I worked at how to use perl not just for writing short shell scripts replacements. I won't be able to find the time to add more slides. But I'm sure you can find great examples online.

    Cheers!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Awesome slides! Very precise and informative. I have a request, could you add some more slides on OOP in perl? It would be great to see a correlation between OOP in say C++ and perl. Thanks!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Very good slides! Thank you!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Crash Course in Perl – Perl tutorial for C programmers

  1. 1. PERLPERL Pathologically Eclectic RubbishPathologically Eclectic Rubbish ListerLister
  2. 2. PerlPerl • Created by Larry WallCreated by Larry Wall in 1987in 1987 • Latest version isLatest version is 5.10.0, released on5.10.0, released on Dec 18Dec 18thth , 2007 to mark, 2007 to mark 2020thth anniversaryanniversary
  3. 3. How It LooksHow It Looks ##!/!/usrusr//binbin//perlperl $;="@{'`|;{'^'!.|-'}";$.++;$.++;$.++;$_="(.)?";/((?{$_.=$_}).)+$/;@_='~!@#$%^&*($;="@{'`|;{'^'!.|-'}";$.++;$.++;$.++;$_="(.)?";/((?{$_.=$_}).)+$/;@_='~!@#$%^&*( )_+`-=[]{}|;':",./<>? '=~/$_/;@_ _=$;=~/$_/;$_="(.)*?";/((?{$_.=$_}).)+$/;$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;
  4. 4. What’s So Special About It?What’s So Special About It? • 20 years of stability. Has been in production20 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 onMore than 12,000 public modules available on CPAN. Ranging from Databases to WWW.CPAN. Ranging from Databases to WWW. • Friendly community, PerlMongers andFriendly community, PerlMongers and PerlMonks.PerlMonks.
  5. 5. 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 someRuns on all modern operating systems (and some that are not quite… modern)that are not quite… modern) – Standard modules run identically on all supportedStandard modules run identically on all supported platformsplatforms
  6. 6. Why You Should Use ItWhy You Should Use It • Powerful string processingPowerful 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
  7. 7. ConvincedConvinced??
  8. 8. Course OutlineCourse Outline • CodeflowCodeflow • VariablesVariables • ConditionalsConditionals • Sexegers (regular expressions)Sexegers (regular expressions) • Loops and iterationsLoops and iterations • FilesFiles
  9. 9. 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?
  10. 10. CodeflowCodeflow • Perl is an interpreter and executesPerl 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
  11. 11. Your First Perl ProgramYour First Perl Program
  12. 12. Get Yourself Some PerlGet Yourself Some Perl • Two flavors of Perl are available forTwo flavors of Perl are available for Windows. Both are freely downloadable:Windows. Both are freely downloadable: – ActiveState PerlActiveState 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
  13. 13. 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
  14. 14. VariablesVariables There are 5 data types in Perl:There are 5 data types in Perl: 1.1. ScalarScalar 2.2. ArrayArray 3.3. HashHash 4.4. File handles and constantsFile handles and constants 5.5. Subroutines (functions)Subroutines (functions) Perl is case-sensitive!Perl is case-sensitive!
  15. 15. 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 declarePerl 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 like a number.a number.
  16. 16. 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
  17. 17. 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!”;
  18. 18. String ModifiersString Modifiers U – translate rest to uppercaseU – translate rest to uppercase print “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 lowercaseL – translate rest to lowercase print “I LIKE /LLOWERCASE”;print “I LIKE /LLOWERCASE”; I LIKE lowercaseI LIKE lowercase - Backslash - Backslash n – Line feedn – Line feed r – Carriage returnr – Carriage return E – Early terminator for U, LE – Early terminator for U, L
  19. 19. 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);
  20. 20. Using ArraysUsing Arrays @x = (3, 1, 4);@x = (3, 1, 4); print @x; => 314print @x; => 314 print “@x”; => 3 1 4print “@x”; => 3 1 4 print $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.
  21. 21. 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
  22. 22. Array Operations – Push/PopArray Operations – Push/Pop @@stack = (); # declare an empty arraystack = (); # declare an empty array push(@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 @stackn”;print “Stack is @stackn”; 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 @stackn”;Print “Stack is @stackn”; Stack is 1 2 3 4Stack is 1 2 3 4
  23. 23. Array Operations – Shift/UnshiftArray Operations – Shift/Unshift @list = (); # declare an empty list@list = (); # declare an empty list unshift(@list, 1); # (1)unshift(@list, 1); # (1) unshift(@list, (2, 3)); # (2, 3, 1)unshift(@list, (2, 3)); # (2, 3, 1) Print “List is @listn”;Print “List is @listn”; 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 @listn”;Print “List is @listn”; List is 3 1List is 3 1
  24. 24. Array Operations – SortArray Operations – Sort @fruits = qw(Oranges Apples Bananas);@fruits = qw(Oranges Apples Bananas); @sorted = sort(@fruits);@sorted = sort(@fruits); print “I grow: @sortedn”;print “I grow: @sortedn”; I growI grow:: Apples Bananas OrangesApples Bananas Oranges Sort creates a new copy of array, and neverSort creates a new copy of array, and never modifies input.modifies input.
  25. 25. Array Operations – Join/SplitArray Operations – Join/Split @array = (“Apples”, “Bananas”, “Oranges”);@array = (“Apples”, “Bananas”, “Oranges”); print join(“n”, @array);print join(“n”, @array); ApplesApples BananasBananas OrangesOranges $csv = “50,10,20”;$csv = “50,10,20”; @elements = split(‘,’, $csv);@elements = split(‘,’, $csv); print “Elements: @elementsn”;print “Elements: @elementsn”; Elements: 50 10 20Elements: 50 10 20
  26. 26. 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 @slicen”;print “Slice is @slicen”; 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
  27. 27. 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 @valuesn”;print “Removed @removed, left with @valuesn”; 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 @valuesn”;print “Spliced into @valuesn”; Spliced into 1 a b c 5Spliced into 1 a b c 5
  28. 28. 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’};
  29. 29. 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);
  30. 30. 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
  31. 31. ConditionalsConditionals TypicalTypical if/elsif/elseif/elsif/else code block:code block: ifif (($var1 > $var2$var1 > $var2) {) { print “$var1 > $var2n”;print “$var1 > $var2n”; }} elsifelsif (($var1 < $var2$var1 < $var2)) {{ print “$var1 < $var2n”;print “$var1 < $var2n”; } else {} else { print “$var1 == $var2n”;print “$var1 == $var2n”; }}
  32. 32. 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 ! $! $exprexpr not $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( ~
  33. 33. 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 blockAfter 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 takes several lines!!several lines!! if ($a < $min) {if ($a < $min) { $a = $min;$a = $min; }} AH! YOU’RE IN LUCK!AH! YOU’RE IN LUCK!
  34. 34. 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;
  35. 35. 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”;
  36. 36. More About ConditionalsMore About Conditionals Perl usesPerl uses early-outearly-out expression evaluationsexpression 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!”;
  37. 37. 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; # empty print $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 ofA simple typo can end up in hours of debugging.debugging. Luckily:Luckily:
  38. 38. Last Two Notes About VariablesLast Two Notes About Variables
  39. 39. use strictuse strict • use strict;use strict; at the beginning of the perlat 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 invariable that wasn’t declared will result in error.error. use strict;use strict; my $name = “Johnny”;my $name = “Johnny”;
  40. 40. Two Last Notes About VariablesTwo Last Notes About Variables You can determine in run time if a variableYou 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;
  41. 41. Regular ExpressionsRegular Expressions Perl has native RE supportPerl 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”; }}
  42. 42. 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
  43. 43. Matching With REMatching With RE $$str = “I like coffee”;str = “I like coffee”; if ($str =~ /I likeif ($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
  44. 44. 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 /g to replace all matches (not just the first).to replace all matches (not just the first).
  45. 45. 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
  46. 46. RE ConditionalsRE Conditionals Positive Matching:Positive Matching: if ($nameif ($name =~=~ /stein$/(/stein$/( {{ print “Smarty!”;print “Smarty!”; }} Negative Matching:Negative Matching: if ($nameif ($name !~!~ /stein$/(/stein$/( {{ print “Nope!”;print “Nope!”; }}
  47. 47. diedie!! Damage control with die and warn. Die (with optional parameter(, prints anDamage control with die and warn. Die (with optional parameter(, prints an error message and stops script execution. Warn prints warning messageerror 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?
  48. 48. 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
  49. 49. 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: $in”;print “I: $in”; }} # $i is not longer defined at this point# $i is not longer defined at this point
  50. 50. 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 $namen”;print “I am $namen”; }}
  51. 51. Iteration on ArrayIteration on Array More examples:More examples: # anonymous array# anonymous array for $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 loop for (1..15)for (1..15) {{ print “I will not talk in classn”;print “I will not talk in classn”; }}
  52. 52. 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 oldn”;print “$name is $age years oldn”; }} OROR # use keys() to control traverse order# use keys() to control traverse order my %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 oldn”;print “$name is $ages{$name} years oldn”; }}
  53. 53. 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: $in";print “Randomly picked: $in"; }} While-do checks break-statement before executing codeWhile-do checks break-statement before executing code block.block.
  54. 54. 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: $in";print “Randomly picked: $in"; } 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.
  55. 55. 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
  56. 56. Next and LastNext and Last ExamplesExamples:: forfor ((my $imy $i==0; $i<5; $i0; $i<5; $i++)++) {{ next unlessnext unless (($i$i %% 22 ==== 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; }}
  57. 57. 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 line executions.executions. UseUse 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 last system command executed is stored in a variable called $?.system command executed is stored in a variable called $?. Yes, that’sYes, that’s $?.$?.
  58. 58. 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..
  59. 59. 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 files 2.2. Reading and writing to filesReading and writing to files 3.3. Reading text lines from files (and chomp)Reading text lines from files (and chomp) 4.4. Additional conditionals -XAdditional conditionals -X 5.5. File operations (rename, copy, delete)File operations (rename, copy, delete) 6.6. Finding filesFinding files 7.7. Some useful packagesSome useful packages
  60. 60. 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 fileopen(FH, “>>debug.log”) || die “Failed to append file debug.log”;debug.log”;
  61. 61. 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;
  62. 62. Reading from filesReading from files Reading is done using <FILEHANDLE> syntax. The angle brackets areReading 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 fetch as 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.
  63. 63. 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!!
  64. 64. 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. ChopChop 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”;
  65. 65. 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 look like this:like this: while (my $str = <>)while (my $str = <>) {{ chomp $str;chomp $str; print “Got $str”;print “Got $str”; }}
  66. 66. 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’t act like other functions.act like other functions. open(FH, “>debuglog.txt”);open(FH, “>debuglog.txt”); print FH “This is the first linen”;print FH “This is the first linen”; # or# or print(FH “This is the first linen”);print(FH “This is the first linen”); Did you notice there’s no comma (,) after file handle?Did you notice there’s no comma (,) after file handle?
  67. 67. Additional Conditional -XAdditional Conditional -X Perl follows shell script conventions and can determine file accessPerl 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!”;
  68. 68. Renaming FilesRenaming Files Use rename() to rename files, exactly as you would with mv in shell orUse 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, renameNOTE: rename() only works on the same partition. Otherwise, rename will fail. Wait for package File::Copy!will fail. Wait for package File::Copy!
  69. 69. 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!”;
  70. 70. 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); }}
  71. 71. 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 (object oriented file access)oriented file access) use File::Copy – copy and move files (even betweenuse File::Copy – copy and move files (even between partitions)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)
  72. 72. 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 as argument, 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; }}
  73. 73. 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"); foreachforeach $_$_ (@_)(@_) {{ $_ =~$_ =~ s/([a-z]+)/U$1 /g;s/([a-z]+)/U$1 /g; printprint $_$_;; }}
  74. 74. 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 are done. 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 exactly like $_;like $_;
  75. 75. 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, not necessarily alphabetic. There are about 40 of them, below is a list ofnecessarily alphabetic. There are about 40 of them, below is a list of the 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
  76. 76. Functions (subFunctions (sub)) Functions in perl are defined using the “sub” reserved keyword. TheirFunctions 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 not defined 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 (or not, dynamically) any values. Return is done with “return” as same asnot, dynamically) any values. Return is done with “return” as same as other languages.other languages.
  77. 77. Functions (subFunctions (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 }}
  78. 78. Functions (subFunctions (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 a function, as $ is of a scalar).function, as $ is of a scalar). Third expression is a bit different. It assumes thatThird expression is a bit different. It assumes that foofoo was declaredwas declared beforebefore the current expression executes.the current expression executes. Maybe it’s more understandable with an example:Maybe it’s more understandable with an example:
  79. 79. Functions (subFunctions (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;
  80. 80. 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?
  81. 81. Passing argumentsPassing arguments 11 22 33 44 3 4 5 6 7 83 4 5 6 7 8
  82. 82. 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 specify how many parameters are allowed in. Use $ as the number ofhow many parameters are allowed in. Use $ as the number of acceptable arguments.acceptable arguments. sub no_parameters()sub no_parameters() {{ }} sub one_parameter($)sub one_parameter($) {{ }} sub three_parameters($$$)sub three_parameters($$$) {{ }}
  83. 83. 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();
  84. 84. Passing argumentsPassing arguments Shift or array copy returnShift 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 were passed in function call.passed in function call.
  85. 85. 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 => $valuen”;print “$statname: $key => $valuen”; }} }} 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 be merged to that array)merged to that array)
  86. 86. 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);
  87. 87. PointersPointers Access referenced value by typecasting to the correct type:Access referenced value by typecasting to the correct type: mymy $$value = 1;value = 1; mymy $$ref = $value;ref = $value; print “My reference is: $refn”;print “My reference is: $refn”; print “But my real value is $$refn”;print “But my real value is $$refn”; My reference is: SCALAR(0x22a0ac)My reference is: SCALAR(0x22a0ac) But my real value is 1But my real value is 1
  88. 88. 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 "@arrayn";print "@arrayn";
  89. 89. 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 :)
  90. 90. Hash DereferenceHash Dereference Alternatively to hashes, and pointers toAlternatively 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!
  91. 91. 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.
  92. 92. Using Hash Core Subs withUsing Hash Core Subs with$$ $$stuffstuff = ()= ();; $$stuffstuff-->{'items'}>{'items'} == 4;4; $$stuffstuff-->{'locations'}>{'locations'} == 1;1; foreach my $keyforeach my $key ((keyskeys(%(%$stuff$stuff)))) {{ print $keyprint $key . ": " .. ": " . $stuff$stuff-->{$key}>{$key} . ". "nn"";; }} locations: 1locations: 1 items: 4items: 4
  93. 93. Perl PackagesPerl Packages Denoted with .pm extension and withDenoted with .pm extension and with packagepackage pragma.pragma. Packages don’t necessarily mean object orientation. They are simply aPackages 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 telephonyn”;print “The first and best in IP telephonyn”; }} 1;1; Packages must return a positive value. Hence the dummyPackages must return a positive value. Hence the dummy expression ‘1’ at the end.expression ‘1’ at the end.
  94. 94. 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 inMust 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 inMust be defined in VocalTec/Devices/Gateway.pmVocalTec/Devices/Gateway.pm
  95. 95. 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 providing full 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 invocationPackages are only loaded to memory once, and only upon invocation ofof ‘‘use’.use’.
  96. 96. Perl PackagesPerl Packages Core modules are located under C:PerlLib
  97. 97. OOPOOP Perl supports all attributes of a classic objectPerl supports all attributes of a classic object oriented programming scheme.oriented programming scheme. • InheritanceInheritance • EncapsulationEncapsulation • PolymorphismPolymorphism ……. All done by chance. All done by chance
  98. 98. OOP: BlessOOP: Bless Let’s define our first class,Let’s define our first class, Animal,Animal, using the keyword ‘bless’. Sub newusing 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; }}
  99. 99. 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; }}
  100. 100. Accessing ‘thisAccessing ‘this’’ ‘‘this’, ‘self’ and ‘parent’ are not defined in Perl. Whenthis’, ‘self’ and ‘parent’ are not defined in Perl. When calling a sub by instance, the first variable in @_, is thecalling 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();
  101. 101. InheritanceInheritance Inheritance is defined entirely by @ISA variable, andInheritance 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; }}
  102. 102. PolymorphismPolymorphism Polymorphism (Method Overloading) is changing aPolymorphism (Method Overloading) is changing a sub 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’}; }}
  103. 103. PolymorphismPolymorphism Method can call parent implementation atMethod can call parent implementation at will (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’})); }} }}
  104. 104. 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" } }}
  105. 105. 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;
  106. 106. 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;
  107. 107. Best PracticeBest Practice AlwaysAlways 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!’;
  108. 108. 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 as2. 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 of updated variables)updated variables)
  109. 109. Think in CThink in C!! In case you are writing a script with entryIn case you are writing a script with entry point (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();
  110. 110. Best PracticeBest Practice CPAN is there for you! Use it!CPAN is there for you! Use it! If you thought of it, most chancesIf you thought of it, most chances somebody already implemented itsomebody already implemented it http://www.cpan.org/modules/http://www.cpan.org/modules/
  111. 111. QuestionsQuestions?? Email me!Email me! gil@megidish.netgil@megidish.net 

×