Match example

print "Would you like to play a game? "; chomp($_ = <STDIN>); if (/yes/i) { # case­insensitive match   print "In that case, I recommend that  you go bowling.\n"; }

1

$_ = "green scaly dinosaur"; s/(\w+) (\w+)/$2, $1/; #scaly, green dinosaur s/^/huge, /; #"huge, scaly, green dinosaur" s/,.*een//; #Empty replacement:"huge dinosaur" s/green/red/; # Failed match: still "huge dinosaur" s/\w+$/($`!)$&/; # Now it's "huge (huge !)dinosaur" s/\s+(!\W+)/$1 /; # Now it's "huge (huge!) dinosaur" s/huge/gigantic/; # Now it's "gigantic (huge!) dinosaur"

Substitute example

2

tr example
##### The "s" option ##### my $text = 'good cheese'; $text =~ tr/eo/eu/s; print "$text\n"; # Output is: gud chese ##### The "d" option ##### my $big = 'vowels are useful'; $big =~ tr/aeiou/AEI/d; print "$big\n"; # The first three vowels are made uppercase. # The other two, which have no replacement # character, are deleted because of the "d". 3

Arrays of arrays
#assign to an array a list of list  references @LoL = (        [ "fred", "barney" ],        [ "george", "jane", "elroy" ],        [ "homer", "marge", "bart" ], ); print $LoL[2][2];   # prints "bart" print $LoL[2]­>[2]; #same as before
4

Hash of arrays
%HoL = ( flintstones => [ "fred", "barney" ], jetsons     => [ "george", "jane",  "elroy" ],   simpsons    => [ "homer", "marge",  "bart" ], );

5

@LoH = (      {         lead    => "fred",         friend  => "barney",      },      {         lead   => "george",         wife   => "jane",         son    => "elroy",      },      {         lead   => "homer",         wife   => "marge",         son    => "bart",      },   );

Array of Hashes

6

Alternate quotes
 

print q!I need $5.00!,"\n"; print 'I need $5.00',"\n"; print qq/Today is /, qx/date/; Today is Sun Sep 13 15:25:27 IST 2009 @list=qw/red yellow blue/; @list=( 'red', 'yellow', 'blue');

 

 

7

Predefined variables

$0 - script name $_ - default input and pattern searching space $`,$&,$' - prematch,match,postmatch

$_ = 'abcdefghi'; /def/; print "$`:$&:$'\n"; # prints abc:def:ghi

8

Blocks

We can use “{ }” to group statements Uses lexical scoping Blocks can be named Its like a loop executed once

 

SWITCH: {     if (/^abc/) { $abc = 1; last SWITCH; }     if (/^def/) { $def = 1; last SWITCH; }     if (/^xyz/) { $xyz = 1; last SWITCH; }     $nothing = 1; 9 }

Controlling loops
next LABEL; Same as continue in C  Continues from given LABEL.  Executes the continue block also.

LINE: while (<STDIN>) {     next LINE if /^#/;  #skip comments     next LINE if /^$/;  #skip blank lines     ... } continue {     $count++; }

10

Controlling loops cont.
last LABEL;

Same as C break Breaks out of the given loop LABEL Continue block is not executed

LINE: while (<STDIN>) {  last LINE if /^$/; # exit when done  with header     # rest of loop here }
11

Controlling loops cont.
redo LABEL;

Restarts the block without checking condition Continue block is not executed

LINE: while ($line = <ARGV>) {     chomp($line);     if ($line =~ s/\\$//) {         $line .= <ARGV>;         redo LINE;     }     # now process $line }

12

File handling
 

File handles are created using open(fh,loc) Handles are closed with close(fh);
seek FILEHANDLE, POSITION, WHENCE

open(SESAME, "filename"); #read open(SESAME, "+<filename"); #rw open(SESAME, ">filename");  #write open(SESAME, ">>filename"); #append open(SESAME, "| output­pipe­command"); open(SESAME, "input­pipe­command |"); print SESAME "stdout 2\n";
13

Example

Example of file handling given in code csv.pl

14

File testing
#!/usr/bin/perl $file=perl.test; print "File is readable\n" if ­r  $file; print "File is writable\n" if ­w  $file; print "File is executable\n" if ­x  $file; print "File is a regular file\n" if ­f $file; print "File is a directory\n" if ­d $file; print "File is text file\n" if ­T $file;
15

Command line arguments

@ARGV – contains command line arguments.

#!/usr/bin/perl die "$0 requires an argument.\n" if $#ARGV  < 0 ; print "@ARGV\n";    # Print all arguments print "$ARGV[0]\n"; # Print first argument print "$ARGV[1]\n"; #Print second argument print "There are ", $#ARGV + 1,"  arguments.\n"; print "$ARGV[$#ARGV] is the last one.\n";  
16

Procedures
Declaration Syntax: sub proc [(prototype)] block  Arguments are pass by value in @_

sub myadd($$) {         ($x, $y)=@_;         print $x + $y,"\n";       return $x+$y; } &myadd($a, $b); # Okay myadd(5, 2); #also Okay myadd($a, $b, $c);    # Too many arguments
17

local ,my and our variable

my variables - lexically scoped and private to

package.

local variables - same as my but dynamically

scoped

our - variables are used to declare global variables

18

#Difference between my and local $friend="Louise";        # Global variables $pal="Danny"; print "$friend and $pal are global.\n"; sub guests { my $friend="Pat"; local $pal="Chris"; print "$friend and $pal are welcome guests.\n"; &who_is_it;      # Call subroutine } sub who_is_it { print "still have global friend,$friend,here.\n"; print "But your pal is now $pal.\n"; } &guests;                # Call subroutine print "Globals are back:$friend and $pal.\n"

19

eval

eval executes given expression

&RANGEVAL(20, 30, '$foo[$i] = $i'); sub RANGEVAL {     local($min, $max, $thunk) = @_;     local $result = "";     local $i;  # Presumably $thunk makes reference to $i     for ($i = $min; $i < $max; $i++) {         $result .= eval $thunk;     }     $result; 20 }

references
 

\varname - is used to get references Same as & in C

$num=5; $p = \$num; print 'The address assigned $p is ', $p,  "\n"; print "The value stored at that address is  $$p \n";
21

References cont.

References may be used to create and access unnamed array,hashes and functions

my $arrayptr=\@array;  #pointer to an  array my $scalarptr=\$scalar;#pointer to a  scalar my $hashptr=\%assoc_array; #pointer to a  hash my $funcptr=\&subroutine; #pointer to a  subroutine

22

@toys = qw( Buzzlightyear Woody Thomas Pokemon ); $num = @toys; %movies=("Toy Story"=>"US",              "Thomas"=>"England",              "Pokemon"=>"Japan",             ); $ref1 = \$num;        # Scalar pointer $ref2 = \@toys;       # Array pointer $ref3= \%movies;      # Hash pointer print "There are $$ref1 toys.\n"; print "They are: @$ref2.\n"; while( ($key, $value) = each ( %$ref3 )){ print "$key­­$value\n"; } print "His favorite toys are $ref2­>[0] and  $ref2­>[3].\n"; print "The Pokemon movie was made in $ref3­ 23 >{'Pokemon'}.\n";

Aliasing

typeglobs are used for creating aliases.
*varname - creates an typeglob

Given: *alias = *var; Then: $alias refers to the scalar $var
@alias refers to the array @var      $alias{string} refers to an element of a hash %var *array=\@array; *scalar=\$scalar;
24

$colors="rainbow"; @colors=("red", "green", "yellow" ); &printit(*colors); sub printit{ local(*whichone)=@_;   # Must use local print *whichone, "\n"; $whichone="Prism of Light"; $whichone[0]="PURPLE"; } print "Out of subroutine.\n"; print "\$colors is $colors.\n"; print "\@colors is @colors.\n";
25

Symbolic references

When we dereference a value that's not reference

$name = "bam"; $$name = 1;              # Sets $bam ${$name} = 2;            # Sets $bam ${$name x 2} = 3;        # Sets $bambam $name­>[0] = 4;          # Sets $bam[0] @$name = ();             # Clears @bam &$name();                # Calls &bam()

can be stopped using

use strict 'refs';
26

Packages
Packages are used for namespace management  Default package is main  A separate symbol table per package

package main; $name = "Susan"; my $birthyear = 1942; print $birthyear; package nosy; print "Hello $main::name.\n"; print "You were born in  $main::birthyear?\n";
27

BEGIN and END

BEGIN blocks are executed the moment they are defined END blocks are executed when interpreter exits

die "green\n"; END   { print "blue\n" } BEGIN { print "red\n" }

28

Modules

Reusable package defined on a separate file with .pm extension Its like class of OO-paradigm

e.g.
package      Fred; require      Exporter; @ISA       = qw(Exporter); @EXPORT    = qw(func1 func2); @EXPORT_OK = qw(@listabob %harry func3);
29

Example use Module (LIST); require Cwd; $here = Cwd::getcwd(); use Cwd; $here = getcwd();

30

Defined function may be overridden example 

use subs qw(chdir chroot chmod chown); chdir $somewhere; sub chdir { ... }

31

Class,Objects,Methods
  

Class is a package that provides methods An object is a reference belonging to a class Methods are subroutines that take references of that class as 1st argument Don't have any special constructor function
bless function is used to mark a reference

belonging to a class.

package Critter; sub new { return bless {}; }

32

Methods

Methods are mainly of two types
− −

Class Methods Instance Methods

Class Methods example-

use Student; $ptr1 = Student­>new();#Create new student

Instance Methods example-

$ptr1­>set("Name", "Jack Sparrow");
33

{ package Grandpa; $name = "Gramps"; sub greetme { print "Hi $Child::name I'm your $name from  package Grandpa.\n"; } } { package Parent; @ISA=qw(Grandpa); } { package Child; $name = "Baby"; print "Hi I'm $name in the Child Package  here.\n"; Parent­>greetme(); }

Inheritance

34

Operator Overloading?
There is a Perl module named overload can be used to Overload Perl's mathematical operations.
package Number;     use overload         "+" => \&add,          "*=" => "muas"; declares function Number::add() for addition, and method muas() in the ``class'' Number (or one of its base classes) for the assignment form *= of multiplication.
35

Memory Management

Uses dynamic memory management using reference count and garbage collection
undef - can be used to free a variable

Storage is recovered but not returned to system
defined expr ­ can be used to check whether

a variable is defined or not.

36

Analysis
     

Readability Writability Expressiveness Simplicity Extensibility Consistency with accepted notations

37

The End

38