variable


quoted strings
 
single quoted
literal string
'' q{} no interpolation
double quoted
literal string
"" qq{} interpolation
command `` qx{} interpolation unless '' is delimiter
word list
qw{} no interpolation
pattern match // m{} interpolation unless '' is delimiter
pattern
qr{} interpolation unless '' is delimiter
substitution
s{}{} interpolation unless '' is delimiter
transliteration
tr{}{} no interpolation except for the first escape sequences (up to named char)
bracketing characters may be:

strings escape sequences
 
\t tab 0x09 ^I
\n linefeed 0x0a ^J
\r carriage return 0x0d ^M
\f formfeed 0x0c ^L
\b backspace (not in a matching pattern where this means word boundary) 0x08 ^H
\a bell 0x07 ^G
\e escape

\033 octal char

\x1b hex char

\x{263a} wide hex char

\cX control char (X being the uncontrolled char)

\N{name} named char

\l lowercase next char (see lcfirst)

\u uppercase next char (see ucfirst)

\L lowercase till \E (see lc)

\U uppercase till \E (see uc)

\Q quote non word characters till \E

\E end case modification or quote

tests

  • if/elsif/else:
  • if ( $o_verb =~ /oyer/ )
    {
        die "error in $line" if $o_verb =~ /envoyer$/;
        $n_group = "36";
    }
    elsif ( $o_verb =~ /oyer/ )
    {
        $n_group = "35";
    }
    else
    {
        die "error in $line";
    }
     
  • if/unless:
  • die "..." if ...
    die "..." unless ...
     
  • switch case:
  • SW_GROUP: {
        if ( $o_group eq "6" )
        {
            ...
            last SW_GROUP;
        }
        if ( $o_group eq "7" )
        {
            ...
            last SW_GROUP;
        }
        ...
        die "unknown group: $o_group";
    }
    or
    while ( <$inputFile> ) {
      SWITCH: {
        /^homme : ([^ ]*) (.*)$/ && do {
            $homme{'prenom'} = $1;
            $homme{'nom'} = $2;
            last SWITCH;
        };
        /^femme : ([^ ]*) (.*)$/ && do {
            $femme{'prenom'} = $1;
            $femme{'nom'} = $2;
            last SWITCH;
        };
        print "unknown parameter: $_";
      }
    }


    loops

  • loop  on a list content:
  • @letters = (a,b,c,d,e,f);
    foreach my $l ( @letters ) {
        ...
    }
     
  • continue
  • a continue block after a  block (typically a while or foreach loop)  is executed before the condition is evaluated once again
     
  • next
  • go to the end of the block, execute the continue block and start the next iteration
    with a label, go to the end of the labelled loop
     
  • last
  • exit the block
    with a label, exit the labelled block
     
  • redo
  • restart the block without executing the continue block and evaluating the conditional
    with a label, redo the labelled block

    while (EXPR) {
      # redo always comes here
      do_something;
    } continue {
      # next always comes here
      do_something_else;
      # then back the top to re-check EXPR
    }
    # last always comes here


    error handling

  • die
  • exit the script with an error message
     
  • warn
  • display an error message and continue
    warn "incorrect value [".$value."]";


    subroutines

    predefined subroutines pattern matching


    predefined variables
    use english; is used to allow the long variables names
    $_
    $ARG
    default input and pattern-searching space
    $1, $2,... sub-parts matching in the last perfomed pattern matching
    $& last string matched by the last succesful pattern match
    $` string preceding the string matching the last successful pattern match
    $' string following the string matching the last successful pattern match
    $.
    $NR
    line number in the last read file
    $/
    $RS
    input record separator or size of the input records
    $,
    $OFS
    output field separator
    $\
    $ORS
    ouput record separator
    $" output separator used for arrays and slices interpolated into a double-quoted string
    $| force a flush after each write
    $@ error message from the last eval operator
    $!
    $ERRNO
    errno ou text describing the last system call error
    $^E more meaningfull description of the last system call error (this is identical to $! on most OSs)
    $? status of the last exited child process (system, wait, paitpid or for a pipe close)
    $SIG signal, warn and die handlers
    $0 name of the script being executed
    (if assigned, will change the argument in ps on some OSs)
    @ARGV arguments passed to the script
    $$
    $PID
    process id of the process
    $<
    $UID
    real user id of the process
    $>
    $EUID
    effective user id of the process
    $(
    $GID
    real group id of the process
    $)
    $EGID
    effective group id of the process
    $^X name of the Perl binary
    @_ arguments passed to the subroutine
    @INC path of the scripts files
    $] version + patchlevel/1000 deprecated, use $^V instead
    $^V version with the format chr(revision).chr(version).chr(subversion)
    can be compared with a literal of the form v5.6.1
    $; subscript separator for multidimensional array emulation
    $[ index of the first element in an array do not use
    $^W
    current value of the warning switch, either TRUE or FALSE

    pragmas
     
    strict unauthorize unsafe constructs
    warnings warn about dangerous constructions
    diagnostics
    display a full explanation of the compilation error messages
    vars predeclare global variable names
    utf8 enable UTF8 in code
    constant define a constant
    use constant PI => 22/7;
    with Perl 5.8.0, it is allowed to write
    use constant {
                   SUNDAY    => 0,
                   MONDAY    => 1,
                   TUESDAY   => 2,
                   WEDNESDAY => 3,
                   THURSDAY  => 4,
                   FRIDAY    => 5,
                   SATURDAY  => 6,
                 };
    in a context that allow barewords, use the syntax FOOBAR() or +FOOBAR since FOOBAR would not work, for example:
    • $hash{CONSTANT()} or $hash{+CONSTANT} instead of $hash{CONSTANT}
    • CONSTANT() => 'value' instead of CONSTANT => 'value'

     

    arrays/lists

    hashes


    array of hashes


    references

  • ref returns the type if its argument is a reference (SCALAR, ARRAY, HASH, CODE, REF, GLOB, LVALUE or package name if the reference has been blessed
  • return false if the argument is not a reference
     
  • bless declares a reference as being referencing an object of a given class
  •  
  • pass a hash reference to a subroutine:
  •   sub bar
      {
          my($h) = @_;
          $k = keys(%$h);
          ...
          print $$h{mykey};
          ...
      }
      ...
      bar(\%myhash);
    operators
    There are 24 levels of precedence:
    left terms and list operators
    left -> infix dereference operator
    if the right side is a ... left must be a ...
    [...] either a hard or symbolic reference to an array
    {...} ... a hash
    (...) ... a subroutine
    a method name or
    a subroutine reference
    an object (i.e. a blessed reference) or
    a class name (i.e. a package name)
    N/A ++ --
    right **
    right ! ~
    unary -


    unary + separator a function name from a parenthesized expression to avoid to consider it as its argument list

    \ create a reference towards what follows it
    left =~
    !~
    binding operators
    left * / % x
    left + -

    . concatenate two strings
    left << >>
    N/A named unary operators
    N/A < > <= >= number comparison

    lt gt le ge string comparison
    N/A == != <=> number comparison

    eq ne cmp string comparison
    left & bitwise boolean operator
    left | ^ bitwise boolean operators
    left && boolean operator
    return the last evaluated value
    left || boolean operator
    return the last evaluated value
    N/A .. ... range operators
    right ?:
    right **= += *= &= <<= &&=
    -= /= |= >>= ||=
    .= %= ^=
    x=
    assignment operators
    left , comma operator
    • in scalar context it evaluates its left argument, throws that value away, then evaluates its right argument and returns that value.
    • in list context, it inserts both its arguments into the list.

    => the => digraph is mostly just a synonym for the , operator except that it forces any word to the left to be interpreted as a string
    N/A list operators
    right not
    left and identical to && but with a very low precedence
    left or identical to || but with a very low precedence

    xor

    objects


    date

  • localtime
  • return the local time
    in a scalar context, return the ctime string
    $now = localtime();
    print(FILEHDL "------------------------\n".
                  $now.
                  "\n------------------------\n");
    in a list context, return the integer values
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);


    file handling



    interaction with the shell

  • get an environment variable
  • $ENV{"FOOBAR"}
     
  • modify the path so commands can be called directly
  • $ENV{"PATH"} .= ":/ddts/bin";
     
  • glob
  • syntax to use if we are sure that there is a single file (we must use a list, otherwise the next call to glob would return undefined)
    my ($anonFile) = glob("$tempdir/*");
     
  • fork and exec a command
  • my $command = $ENV{"SDC_BIN"}."/browser";
    my $p = fork();
    if (!defined($p)) {
        log_mess("Can't fork: $!");
    } elsif ( $p == 0 ) {
        exec $command;
    }
     
  • handle signals
  • sub catch_signal {
      my $sig = shift;
      log_mess("signal $sig catched");
      my $p = get_browser_pid();
      kill "USR1",$p;
    }
    $SIG{"INT"} =  \&catch_signal;
    $SIG{"QUIT"} =  \&catch_signal;
     
  • get the pid of a process on Solaris
  • sub get_browser_pid {
      open(PS,"ps -e -o pid,comm |");
      while ( <PS> ) {
        chomp;
        my ( $pid, $process ) = split;
        if ( $process eq "myprocess" ) {
            close(PS);
            return $pid;
        }
      }
      close(PS);
      return 0;
    }
     
  • get the output of a shell command
  • open(BUGVAL,"/ddts/bin/bugval -i $spr Headline |") or die("failed to get headline of $spr ($!)");
    my $headline = <BUGVAL> or die("failed to get headline of $spr");
    print HTML to_html($headline);
    close(BUGVAL);
     
  • execute a command and wait for its status
  • @cmds = ("netscape", "-remote", "file:".$htmlfile);
    system(@cmds) == 0 or die("failed to communicate with Netscape ($!) --");
    or
    system("netscape -remote file:$htmlfile") == 0 or die("failed to communicate with Netscape ($!) --");
     
  • execute a grep
  • system("/usr/xpg4/bin/grep","-w","-q",$str,glob("*.c")) and print "$str is not used\n";


    predefined functions

  • print
  • print a message on stdout
    print "message\n";
    print a message on stderr
    print STDERR "message\n";
  • printf
  • print a formatted string
  • sprintf
  • return a formatted string
    $s = sprintf "%04d%02d%02d", $year, $month, $day;
     
  • chop
  • remove the last character of a string and return it
    chop($line);
     
  • chomp
  • removes the end of a string if it is $/
    chomp($line);
     
  • crypt
  • password encryption
    $crpwd = crypt($pwd,$salt);
     
  • do
  • execute a script file (in order to load its routines)
     
  • require
  • require Foo::Bar;
    load a module (i.e. execute the script Foo/Bar.pm, we can also write require Foo/Bar.pm)
     
  • use
  • use Foo::Bar;
    load a module and call its import routine (this works only with a bareword)


    Internet

    tricks


    one-liners


    command line flags



    Last update: March 7th, 2006 - Laurent