SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Downloaden Sie, um offline zu lesen
Introduction to Perl
           including Perl 5


                     Phil Spector
           Statistical Computing Facility
              Department of Statistics
          University of California, Berkeley


                             1




                     What is Perl?
Practical Extraction and Report Language
Developed by Larry Wall in the late 1980s
Combines features of awk, sed, grep and shell scripts
Originally developed for UNIX; now available widely
No inherent limitations to the size of problems it can handle




                             2
Some Typical Uses of Perl
   NOT for computational algorithms
   preprocessing input for other programs
   postprocessing output from other programs
   repetitive editing, searching or processing of a series of les
   simpli ed access to system calls
   managing tasks requiring coordination among programs
   emerging as a language of choice for WWW CGI scripts
   prototyping more ambitious projects


                                 3




                         Accessing Perl
Under UNIX, create an executable le whose rst line is
  ! usr local bin perl optional flags
 and whose remaining lines contain your perl program
Alternatively, invoke perl from the command line:
  perl optional flags perl program ...
Some of the ags available include:
 -e - invoke perl with a one line program
 -w - invoke perl in warning mode
 -n - invoke perl with automatic input loop
 -d - invoke perl with symbolic debugger
Flags can be combined. A useful example is
   perl -de 0

which will run the debugger with no program.

                                 4
Variables
      All variables begin with a special symbol:
      $ - scalar      @ - array       - associative array

      Each type of variable has its own namespace
      Variable names are case sensitive:             ,
                                                 $var $Var     and $VAR are
      three di erent variables
      By default, all variables are global
      Perl determines type numeric or character, scalar or array by
      context
      Numbers initialize to 0, characters initialize to 
      Eliminate variables with undef

                                       5




                          System Variables
There are many built-in variables which control the behavior of
perl; each of the variables has a terse name, as well as a one or
more mnemonic ones. To access the long names in the table below,
include the line use English; in your perl program
 Name Long Name                        Name Long Name
  $        $INPUT RECORD SEPARATOR         $       $OUTPUT RECORD SEPARATOR
  $,       $OUTPUT FIELD SEPARATOR         $.      $INPUT LINE NUMBER
  $        $UID                            $       $EUID
  $$       $PROCESS ID                     $      $MATCH
  $!       $OS ERROR                       $?      $CHILD ERROR
  $|       $OUTPUT AUTOFLUSH               $^T     $BASETIME
 $ARGV     name of le being read       @ARGV       array of command line args


                                       6
Arrays
Regular arrays @ are indexed by number - negative numbers
count from the end of the array
The highest index of an array can be found using $array
By default, indexing of arrays starts at 0
 Can be changed with automatic variable $
Associative arrays  are indexed by strings
Associative arrays use curly braces like $ary $value 
Subscripting can be used to create scalars or arrays
  Suppose @T is an array with 10 elements
  @part = @T 0,1,2 ;        array with three elements
  $part = $T 0 ;            scalar
More complex structures can be stored in arrays by using
references
                             7




                        Operators
All the standard binary operators from C
+ - addition - - subtraction        - division * - multiplication
Additional operators
** - exponentiation            . - string concatenation
x - string repetition         .. - range operator 1..3 1,2,3
                                                      


All operators have a corresponding assignment operator
For example $string .= $add concatenates $string and $add
and puts the result into $string
Increment and decrement operators
++ - increments                    -- - decrements
pre x before evaluation, post x after evaluation
                                   


|| is logical or,  is logical and - These di er from the C
operators in that they return the last expression evaluated
instead of 0 or 1. You can also use the words or or and.
                             8
Comparison Operators
Perl provides two sets of comparison operators, one for numbers
and one for strings
It's your responsibility to use the right one the -w ag helps
          Function              Numerical Character
          Equality                ==         eq
          Non-equality            !=         ne
          Less than                          lt
          Greater than                       gt
          Less than or equal        =        le
          Greater than or equal     =        ge
          Comparison               =        cmp



                                  9




                       Quoting Operators
While we generally think of quotes as literal values, perl provides
operators which provide similar capabilities. These are especially
useful if the object to be quoted contains quotes.
    qftextg  - similar to the single quote '. No variable
    interpolation is performed.
    qq text - similar to the double quote . Variable
      f       g

    interpolation is performed
    qx text - similar to the backquote `. After variable
      f       g

    interpolation, the text is treated as an operating system
    command, and its result is returned.
    qw text - returns an array of words from text, equivalent to
      f       g

    quoting each one. No interpolation is performed.
You can use any character you choose in place of the   fg   pair.
                                 10
Simple Examples
   Print only lines with exactly ve elds
     perl -ne 'print if split == 5' filename

   Print lines that are longer than 80 characters
     perl -ne 'print if length              80' filename

   Print the 10th through 20th lines of a le
     perl -ne 'print if $.          = 10  $.    = 20' filename

   Print lines where the third eld is 0
     perl -ne 'print if split 2            == 0' filename

   Change cat to dog
     perl -pe 's cat dog '       filename

   Translate lowercase to uppercase
     perl -pe 'tr     a-z     A-Z      ;'   filename


                                 11




                        Perl Functions 1
Note: Most functions operate on $_ if they have no arguments
      For more information, type perldoc -f functionname.
   chop - removes last character of its argument
   Useful for removing newlines:
       while 
           chop;
            ...     $_ no longer contains a newline



   split   - break a line into words
     @T = split;                       breaks $_ into words,
     @T = split,;                  uses comma as separator
     @w = split      , + ,$in;  uses comma or space


                                 12
Perl Functions 2
join    - combine an array or list
print join ,@T;
$fn = join ,@parts;

keys    - produce array containing the indices of an associative
array
   @thekeys = keysarray;
values  - produce ordinary array containing the values of an
associative array
each - iteratively returns a key value pair from an associative
array, or a null value at the end of the array.
   while$key,$value = eacharray             ...

iterates over all the key value pairs.

                               13




                      Perl Functions 3
index  - returns the position of the rst occurence of a
substring within a string. returns -1 if no match
        $str = the cat in the hat;
        $i = index$str,'cat';

sets $i equal to 4.
substr - extracts part of a string from a larger string

$piece = substr$str,3,5;  5 chars, start at pos. 3
$part     = substr$str,3;           from pos. 3 to the end
$end      = substr$str,-5;          starts 5 chars from end

grep - evaluate an expression for each element of an array, and
  return an array of elements for which the expression was true
@joes = grep joe ,@array;


                               14
Perl Functions 4
map - returns a list resulting from evaluating an expression on
each element of a list.
        @cts = maplength,@text

@cts   will contain the lengths of each element of @text.
eof - returns 1 if the next input   would return end of le.
eval - evaluate a string as if it were a Perl program
unpack - breaks a string into an array using format codes
 Can be used for xed format records or binary data
@T = unpackx3A4A5,$in;  like 3x,a4,a5
@N = unpackd4,$vals;            reads 4 doubles binary

pack   does the opposite of unpack

                              15




                     Perl Functions 5
push   - add an element to the end of an array
push@array,$newval;
pop   - remove and return the last value of an array
$lastvalue = pop@array;
shift   - remove and return the rst value of an array
$firstvalue = shift@array;




                              16
Programming in Perl
All statements must end in a semicolon ;
Blocks of statements are surrounded by curly braces  
Control statements from C: for, while, goto
Additional statements: unless and until
Inside loops, use next and last
Compound statements can eliminate the need for brackets
   Examples:   $x = 3 if $a     $b;
               $new = sub$new until $new      $old;

foreachstatement makes processing arrays easy
   Example: foreach $value @array ...

                           17




                    Reading Input
Basic input operator is angle brackets:
Perl is clever about guring out where input comes from
   Reads from les if their names appear on the command line
   Reads from standard input otherwise
open function creates a lehandle
openFI,filename || die Couldn't open filename;
  Then read from filename with
   $in =   FI ;

Character based input can be performed using the read and
seek functions:

      readFILEHANDLE,$target,$length;
      $success = seekFILEHANDLE,$position,$whence;


                           18
Two Special Cases
With a while statement, input goes to $_
   while         or while FILEHANDLE 
          ...      each line is read into $_



This is so useful, it's implemented as the -n ag.
If a wildcard is in the brackets, it is expanded and $_ set to
each lename
  while *.c 
       openFI,$_;
            . . .




                              19




                       Filehandles
Special cases:
   openFH, filename;            open for input only
   openFH, filename;            open for output only
   openFH, $filevar;            same using variable
   openFH,     filename;  open for append
   openPI,command|;             open pipe from 'command'
   openPI,|command;             open pipe to 'command'
Automatic Filehandles:         ,         ,
                         STDIN STDOUT STDERR

   $response =      STDIN ;
   chop$response;

Input record separator de ned by automatic variable $
Setting $ = 0777 causes the whole le to be read into a scalar
Reading a lehandle into an array reads the whole le
                              20
References
References are a way of storing a link to one variable as the value
of another variable, and can be used to produce structures of
arbitrary complexity.
Perl will never automatically dereference your references you
always need to explicitly dereference them.
To explicitly make a variable a reference, you can use the backslash
  operator:
              $thearray =     @array;
To dereference a reference, surround the reference name with curly
braces  , and precede it with the appropriate operator:
  $value = $ $thearray        2 ;          extract a scalar
  @vals      = @ $thearray    2..5 ;  extract an array slice

You can check to see whether a variable is a reference using the
ref function, which returns  for a regular variable.

                                    21




                       References cont'd
One of the most useful ways of using references is to create an
array of arrays, similar to C's multiply subscripted arrays. In these
examples, the arrays are created implicitly.
 @ $test harry       = 5,3,2,9;           makes an array
 print $test harry      3 ;                 prints 9


 $x 1    3   = 17;                            creates x on the fly

When an element of an array is a reference to an array, you must
dereference it correctly to use it as an array:
              push@ $test harry         ,17;

Double subscripts are shorthand for the      -    operator:
        print $test harry     2 ;           prints 2
        print $test harry -       2 ;       same as above

                                    22
Example: Rearranging output from rusers
The UNIX rusers command lists users on each machine on a
network. We'll rearrange the output to give a list of users and the
machines to which they are logged in:
! usr local bin perl
openRU,rusers `stathosts`|;
while RU 
        chop;
        @T=split' ';
        $machine = shift@T =~ s .* ..* $1 ;
        foreach $t @T
                push@ $usr $t ,$machine
                        if!grep ^$machine$ ,@ $usr $t   ;



@users = sortkeysusr;
foreach $u @users
        printfsss n,$u,length$u   8 ?  t t :  t,
                join ,@ $usr $u ;


                                 23




                   rusers    Example cont'd
The rusers output looks like:
alpha.Berke joe fred sam
beta.Berkel fred fred fred fred harry
gamma.Berke sue john sam
                   ...

The output from the perl script looks like:
fred               alpha beta
harry              beta
joe                alpha
john               gamma
sam                alpha gamma
sue                gamma
                  ...


                                 24
Example: Finding and killing jobs
Suppose we want a command which will nd telnet sessions which
we have initiated and selectively eliminate them.
The UNIX ps command can list the telnet sessions. We could then
present the process id to the kill command. We'll use perl to
automate the process.
! usr local bin perl
@ps = ` usr ucb ps auxww | grep telnet`;
foreach $ps @ps
        @T = split ,$ps;
        if$T 10 =~ ^telnet 
                printKill session to $T 11 ? ;
                $resp = STDIN ;
                chop $resp;
                kill 15,$T 1 if$resp eq y;




                               25




                           Printing
Remember that variables are expanded inside of quotes, making
many printing tasks simple.
   print  function
      $, is eld separator
      $ is record separator

   printf function behaves like its counterpart in C

   You can specify a lehandle as an alternative to STDOUT
           print STDERR Error in input line $. n;

   Simpli ed printing of errors and warnings
   warn - prints message with newline to standard error
   die - like warn, but exits after printing


                               26
More on Printing
    Use escape characters to literally print special characters
             $cost = 100;
             print The cost is        $$cost n;

    results in
    The cost is $100

    Include large blocks of text using perl's here-is syntax:
    print           identifier;
               

        text to be printed
              

    identifier
    Extensive formatted printing can be done with format        write


                                       27




                                  Sorting
The sort function by default performs a lexicographical sort.
Alternatively, a subroutine or block of statements can be provided.
Plain sort gives lexicographical sort:
  @snames = sort@names;

Using    =    gives numerical sort note no comma:
  @svals       = sort $a     =   $b        @values;

Sorting an associative array based on keys:
  @skeys = sortkeysarray;
  foreach $key @skeys
          push@sarray,$array $key ;


Sorting keys based on the values of an associative array:
 @skeys = sort $array $a              =     $array $b   keysarray;

                                       28
Functions which return Arrays
You can use a list with individual members instead of an array
        $first, $last = split ,$name;

You can extract just part of a returned array
 first word from $_ is stored in $first
   $first = split 0 ;
 second through fifth words in $line
   @some = split ,$line 2..5 ;

Setting a scalar to an array results in the number of elements
 $num is number of comma-separated items in $line
   $num = split,,$line;


                             29




                        Examples
Finding Unique Lines in a File
! usr bin perl -n
 -n puts the perl program in a while           loop
  print if$x $_ ++ == 0;



Finding the Longest Line in a File
! usr bin perl -n
chop;                  remove the newline
$ll = length;
$maxl = $ll if $ll       $maxl;
print $maxl n if eof;


                             30
Example: Keeping Track of Number of Fields
! usr bin perl
while     
           $n = split;
           $ct $n ++;



@skey = sort $a        =   $b    keysct;


foreach $key @skey
           print $key: t$ct $key         n;




                                     31




                        Regular Expressions
   =~    operator allows testing or substitution
   $in =~ m r e                   returns 1 if r e is in $in
   $in !~ m r e                   returns 1 if r e is not in $in
     The m is optional; you could use      r e    instead.
   $str =~ s old new ;                   changes old to new in $str
   $new = $save =~ s old new ;               doesn't change$save

   Variables are expanded inside of regular expressions
   Regular expressions can be arguments to split or to set $
Note: With the m ... or s ... operators, you can replace the
   with any character you choose, or you can use pairs of or  fg

as delimiters. Avoid using ? as a delimiter.

                                     32
Constructing Regular Expressions
Regular Expressions can contain any combination of:
   Literal Characters
   Note: Always escape . ^ $ + ? *                  |
   Character Classes
    Characters surrounded by square brackets  
   Negated Character Classes
    First character in brackets is a caret ^
   Escape Characters
    n newline               f formfeed       t tab
    b  word boundary       d digit          w alphanumeric
    B non-boundary          D non-digit      W non-alphanumeric
   Octal or Hexadecimal Characters
     nnn - octal       xnn - hexadecimal
   - Represents a backspace in a character class
                                         33




               Constructing Regular Expressionscont'd
      Operators within Regular Expressions
       ^          anchors expression to beginning of target
       $          anchors expression to end of target
       .          matches any single character except newline
       |          separates alternative patterns
                groups patterns together
       *          matches 0 or more occurrences of preceding entity
       ?          matches 0 or 1 occurrences of preceding entity
       +          matches 1 or more occurrences of preceding entity
         n        matches exactly n occurrences of preceding entity
         n,       matches at least n occurrences of preceding entity
         n,m      matches between n and m occurrences


                                         34
Grouping in Regular Expressions
In addition to grouping alternations, parentheses are used in
regular expressions to tag sub-expressions which can be referred to
later. The expression contained by the i-th set of parentheses
counting from the left is referred to as i on the left-hand side of
a substitution, and $i anywhere else. If you want to use
parentheses for just grouping, without tagging the enclosed
sub-expression, use ?: and  for grouping.
For example, the following program identi es the rst occurrence in
each line of input of two identical words in a row:
        if   b w+ + 1    b
              print '$1 appears twice in line $. n';


Note that the tagged expression is referred to as 1 in the regular
expression itself, but as $1 outside the regular expression.
                                   35




               Modi ers for Regular Expressions
A number of letters can be placed after the nal delimiter of a
regular expression to modify some aspects of the matching process
    i - Makes the match case-insensitive.
    g - Operates on all occurences of the regular expression,
    instead of just the rst, which is the default behavior.
    s - Allows . to match newline along with everything else
    m - Changes the meaning of ^ and $ anchors so they are
    meaningful for each logical line. You can always use A and Z
    to mean the beginning and end of the input.
    e - Treats the right hand side of the s ... ... operator as a
    Perl expression instead of simply text.
    x - Ignore whitespace and comments inside of the regular
    expression - useful for formatting complex regular expressions.
                                   36
Return Values from Regular Expression Operators
The values returned from the m ... and s ... ... operators
are di erent depending on the context in which they are used
    m ...   operator
       When used as a scalar, returns 1 if the match was
       successful, 0 otherwise
       When used as an array, returns a list of tagged items.
    m ... g operator
    When used as an array, returns a list of tagged items
    corresponding to as many matches as were found.
    s ... ... operator
    In scalar or array context, returns the number of substitutions
    which actually took place.

                                 37




               Examples of Regular Expressions 1
Change NA to . period
       s NA .
Problem: NAME gets changed to .ME
Solution: Use b to specify word boundaries
       s    bNA b   .

The s command returns a count of the number of substitutions
which are carried out, so it can be used to count occurrences of
regular expressions:
      while    
           $i = s   bNA b   .   g;
           print Too many missing in line $. n if $i             5;




                                 38
Examples of Regular Expressions 2
Reverse the order of two words
       s  w+  w+ $2 $1 ;

$line = one two three four;
$line =~ s  w+  w+ $2 $1 ;           two one three four
$line =~ s  w+  w+ $2 $1 g;           two one four three
Find a word followed by a number
   if  w+  d+ 
         print word is $1, number is $2 n;


Note that $1 and $2 retain their values after the regular expression.


                                 39




             Examples of Regular Expressions 3
Add one to a series of line numbers at the beginning of each line.
       s ^ d+ $1 + 1 e;

Since we can't add 1 to a number using text, the e modi er was
used.
Function calls which return appropriate types can also be used with
the e modi er. For example, to convert numbers to their
hexadecimal representation, you could use the sprintf function:
$str = 125 234 321;
$str =~ s  d+ sprintfx,$1 ge;            7d ea 141




                                 40
Greediness of Regular Expressions
Consider extracting URLs from a document. One strategy could be
to nd strings which start with http or ftp, followed by a colon :
and which end with a character which is not a valid character for a
URL, leading to a pattern like
            ?:http|ftp:.* ^-_       .~ w

But if we use this pattern on text such as
Go to http:    www.info.com and report any problems.

we would nd that $1 will be set to
http:   www.info.com and report any problems.

since the end of line allowed a longer match than the address alone.

                                 41




        Greediness of Regular Expressions cont'd
One way to solve the problem is to replace the occurence of .,
which represents any character, with a more speci c character
class. In this case, we could use any character which is a valid part
of a URL:
           ?:http|ftp: -_      .~ w * ^-_     .~ w

A more general approach is to use a question mark ? after the
quanti er to tell perl to nd the smallest string that matches
instead of the longest, which is the default:
           ?:http|ftp:.*? ^-_       .~ w

Either of these approaches will extract only the URL and not the
text which follows.

                                 42
Iterative Use of the m    ... g    operator
When used inside a while loop, the m ... g operator can be used
to process multiple occurences of regular expressions. For example,
suppose we wanted to process a le containing email addresses, in
order to count how many address were in each domain. Recall
email addresses are in the form username@domain.name. The
following program would process each address, even if there were
multiple addresses on the line:
while   
         chop;
         while    b w+@ ^@ + g
                   $count $2 ++;



foreach $key keyscount
        print $count $key addresses from $key n,



                                  43




             More Examples of Regular Expressions
    Remove trailing newline alternative to chop
         s    n$   ;

    Eliminate leading 0s in a line of numbers
         s    b0+ d $1 g;

    Removing the leading portion of a pathname
         $tail = $path =~ s.+ .*$1;

    Capitalize the rst letter of rst word in a line
         s ^ a-z      U$1 E ;

    Remove comments  from a line
         $line =~ s .*.* $1 ;



                                  44
Using Perl to Edit Multiple Files
Two ags are especially useful when using perl as a stream editor:
   -p sets up input loop and automatically prints $_
   -i allows inplace editing an extension   backup copy
For example,
perl -pe 's     bNA b   .   g' old.dat      new.dat

would change all NAs to periods in old.dat, and write to new.dat
perl -i.bak -pe 's      bNA b    .    g' *.dat

would do the same in place for all les ending with .dat, creating
copies with .bak appended to the names.
This command works well with the UNIX find command:
perl -i.bak -pe 'sINCL=-I..INCL=-I.. -I.. include'
        `find . -name Makefile -print`

                                 45




          Interacting with the Operating System
    system   lets you execute an operating system command
    backquotes ` ` or the qx operator let you capture output
                                fg

    into a perl variable
       retains newlines
       multiline output can be captured in an array
       variable expansion takes place inside of backquotes
    Perl provides functions for many operating system calls
    chdir, kill, sleep, wait, exec, fork, unlink, mkdir, etc.

    The associative array ENV contains environmental variables
    $ENV USER , $ENV EDITOR , etc.



                                 46
File System Operators
As in many shells, perl o ers operators for simpli ed le queries
      Op Tests           Op Tests          Op Tests
      -r Readable        -w Writable       -x Executable
      -l Link            -e Existence      -f Plain File
      -d Directory       -T Text           -B Binary
Example:
  $prefix =  usr local help ;
  $filename = $prefix.$topic;
  warnNo help file for $topic unless -f $filename;




                                47




      Example: Executing Commands on a Network

! usr local bin perl


@machines = winnie,pooh,kestrel,eeyore;


foreach $machine @machines
           $job = `rsh $machine ps aux | grep $ARGV 0 `;
           print Jobs on $machine: n$job n if$job;




                                48
Formatted Output
    The format statement allows you to de ne a template for
    output produced by the write function. Substitutions are
    made as follows:
     @          left justify as many columns as there are s
     @          right justify as many columns as there are s
     @|||       center as many columns as there are |s
    Specify the variables to be printed below the format lines,
    separated by commas
    Final line of the format should have a single period
    You can specify a header to appear on top of each page
    $= is the page size

                                 49




                Example of Format Statement
format STDOUT_TOP =
Name                                  Office   Extension
.
format STDOUT =
@                                @               @
$name,$office,$ext
.
while   
       $name,$office,$ext = split,;
       write;




                                 50
Example of Format Statement cont'd
The previous example would convert
Fred Smith,425,x7743
John Jones,372,x4450
Harold Johnston,421,x4622

to:
Name                                    Office   Extension
Fred Smith                                 425       x7743
John Jones                                 372       x4450
Harold Johnston                            421       x4622




                                   51




                       Creating Subroutines
      De ne a subroutine using
      sub subroutine name
         statements


      The last expression evaluated is returned, or use return
      Arguments to subroutines are passed as one list through @_ :
       First arg is $_ 0 , second is $_ 1 , etc.
      Arguments other than scalars must be passed to subroutines as
      references
      Recall by default perl variables are global. The my function can
      create local variables within the subroutine.
      Perl subroutines may be recursive
                                   52
Using Subroutines
      Call with subargs...
      Note that parentheses and arguments are optional
      Include subroutines using the require statement
        require 'file.pl';

      The require statement searches the directories in @INC, which
      will always contain the current directory.
      To read in a subroutine using require, the last line must be
       1;




                                   53




                Example: Prompting for a Password
sub getpass
      my$prompt = $_       0 ? Password: : $_ 0 ;
      systemstty -echo;
      printSTDERR $prompt;
      $pass =    STDIN ;
      systemstty echo;
      chop$pass;
      printfSTDERR  n;
      return $pass;


1;

If the subroutine was in a le called getpass.pl, use:
     require 'getpass.pl';
     $secret = getpass;        or getpassPrompt:;

                                   54
Example: Counting Strings in Files
Suppose we wish to write a subroutine which will accept a list of
  les as its rst argument, a regular expression as its second
argument, and which will return an array containing the number of
times the regular expression occurs in each of the les. Since
arguments to perl subroutines are passed as a single list, the rst
argument must be a reference to a list. In the subroutine on the
next slide, the list will be stored in a local array called files
through the use of the my function. To call a subroutine such as
this, a reference must be passed as the rst argument, for example
    @myfiles = test.1,data,README;
    @cts = countpat @myfiles,duck;




                                55




       Example: Counting Strings in Files cont'd
sub countpat
  my@files = @ $_ 0      ;
  my$pat      = $_ 1 ;
  my@res = ;
  foreach $f @files
     openFI, $f || die Couldn't open $f;
     $ct = 0;
     while FI 
          $ct++ while s $pat     ;


     closeFI;
     push@res,$ct;


  return@res;



                                56
Example: Resolving Links recursion
On many systems there are long chains of links, so using ls to nd
where a le really is can be confusing. Since perl functions can be
called recursively, they provide a simple solution.
The strategy is to write a function which prints a given lename,
and, if it is a link, to follow the ls convention of using - to point
to the link. This process is continued until a le which is not a link
is found.
Since many links are stored as absolute pathnames, we'll need a
function which takes a relative pathname and makes it absolute.
That turns out to be the hard part. The main loop and printing
program reslink are shown on the next slide; the pathname
resolution program resdir is on the slide after the next.

                                 57




              Example: Resolving Links cont'd
 main loop
foreach $name @ARGV
         reslink$name;
           printf n;


 resolve links using -  notation
sub reslink
         printfs,$_ 0 ;
         if! -e $_ 0       printfdoes not exist


         if-l $_ 0 
                   printf -     ;
                   reslinkresdir$_ 0 ;




                                 58
Example: Resolving Links cont'd
sub resdir
          my $dir = $_ 0 ;
          my $now = readlink$dir;
          ifsubstr$now,0,1 ne  
 not absolute pathname
                  $i = 1;
                  @n = split ,$dir;
 resolve relative links ..
                  ifindex$now,..        -1
                             $i++ while $now =~ s . . ;


                  $now = join ,@n 0..$n-$i ,$now;


          return $now;



                                59




                 Command Line Arguments
   Arguments are stored in the array @ARGV
   First argument is $ARGV 0 , second is $ARGV 1 , etc.
   Getopts subroutine

      Argument to Getopts is a string of characters
      Options with arguments are followed by : in the string
      Variables of the form $opt_letter are set appropriately
      Options and arguments are removed from @ARGV
require 'getopts.pl';
Getoptsan:x;

Running
program -a -n 100
will set $opt_a to 1, $opt_n to 100, and $opt_x to 
                                60
Resources
Manual page man perl - provides a overview of the other
25 ! manual pages describing perl
Books: Note: 2nd edition is perl5, 1st edition is perl4
Learning Perl, 2nd Edition by Randal L. Schwartz
Programming Perl, 2nd Edition by Larry Wall  Randal L.
Schwartz
Perl Cookbook by Tom Christiansen  Nathan Torkington
 all three published by O'Reilly and Associates
Internet Newsgroup: comp.lang.perl
FAQ from convex.com pub perl info faq anon. ftp
Reference Card part of Programming Perl
from CPAN archive  doc perlref-5.004.1.tar.gz

                           61




                  Resourcescont'd
Source is available from CPAN archives try www.perl.org or
check http: language.perl.com CPAN for more
information.
The o cial perl website maintained by Tom Christiansen is
located at http: www.perl.com .
http:   www.eecs.nwu.edu perl perl.html   is another good
starting point for nding WWW perl resources.



                           62

Weitere ähnliche Inhalte

Was ist angesagt? (18)

Perl_Part1
Perl_Part1Perl_Part1
Perl_Part1
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
A regex ekon16
A regex ekon16A regex ekon16
A regex ekon16
 
Regular expressions in Perl
Regular expressions in PerlRegular expressions in Perl
Regular expressions in Perl
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Awk essentials
Awk essentialsAwk essentials
Awk essentials
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
 
Sed tips and_tricks
Sed tips and_tricksSed tips and_tricks
Sed tips and_tricks
 
Perl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsanePerl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally Insane
 
00 ruby tutorial
00 ruby tutorial00 ruby tutorial
00 ruby tutorial
 
Regular expressionfunction
Regular expressionfunctionRegular expressionfunction
Regular expressionfunction
 

Andere mochten auch

Assertion And Holistic Health Dr. Shriniwas Kashalikar
Assertion  And  Holistic Health  Dr. Shriniwas KashalikarAssertion  And  Holistic Health  Dr. Shriniwas Kashalikar
Assertion And Holistic Health Dr. Shriniwas Kashalikardrsolapurkar
 
H O L I S T I C H E A L T H Dr
H O L I S T I C  H E A L T H  DrH O L I S T I C  H E A L T H  Dr
H O L I S T I C H E A L T H Drdrsolapurkar
 
NutritionCamp. Dietary Supplements, functional food and nutraceuticals - Mari...
NutritionCamp. Dietary Supplements, functional food and nutraceuticals - Mari...NutritionCamp. Dietary Supplements, functional food and nutraceuticals - Mari...
NutritionCamp. Dietary Supplements, functional food and nutraceuticals - Mari...Barilla Center for Food & Nutrition
 
Making your consortium sustainable: advocacy and communication
Making your consortium sustainable: advocacy and communicationMaking your consortium sustainable: advocacy and communication
Making your consortium sustainable: advocacy and communicationKristīne Pabērza
 
CERT - EXXONMOBIL - RECORD MANAGEMENT - PART 11
CERT - EXXONMOBIL - RECORD MANAGEMENT - PART 11CERT - EXXONMOBIL - RECORD MANAGEMENT - PART 11
CERT - EXXONMOBIL - RECORD MANAGEMENT - PART 11Maria Raju
 
O papel da tutoria no desenvolvimento curricular
O papel da tutoria no desenvolvimento curricularO papel da tutoria no desenvolvimento curricular
O papel da tutoria no desenvolvimento curricularMaria Casanova
 
The Adbrand Battles Presentation Final Draft
The Adbrand Battles Presentation Final DraftThe Adbrand Battles Presentation Final Draft
The Adbrand Battles Presentation Final DraftEric Floresca
 
Fall_2008_CS601_W1_Tyngsboro
Fall_2008_CS601_W1_TyngsboroFall_2008_CS601_W1_Tyngsboro
Fall_2008_CS601_W1_Tyngsborotutorialsruby
 

Andere mochten auch (20)

JavaScript
JavaScriptJavaScript
JavaScript
 
Assertion And Holistic Health Dr. Shriniwas Kashalikar
Assertion  And  Holistic Health  Dr. Shriniwas KashalikarAssertion  And  Holistic Health  Dr. Shriniwas Kashalikar
Assertion And Holistic Health Dr. Shriniwas Kashalikar
 
H O L I S T I C H E A L T H Dr
H O L I S T I C  H E A L T H  DrH O L I S T I C  H E A L T H  Dr
H O L I S T I C H E A L T H Dr
 
Fyp in full
Fyp in fullFyp in full
Fyp in full
 
NutritionCamp. Dietary Supplements, functional food and nutraceuticals - Mari...
NutritionCamp. Dietary Supplements, functional food and nutraceuticals - Mari...NutritionCamp. Dietary Supplements, functional food and nutraceuticals - Mari...
NutritionCamp. Dietary Supplements, functional food and nutraceuticals - Mari...
 
Making your consortium sustainable: advocacy and communication
Making your consortium sustainable: advocacy and communicationMaking your consortium sustainable: advocacy and communication
Making your consortium sustainable: advocacy and communication
 
geoext_dwins
geoext_dwinsgeoext_dwins
geoext_dwins
 
CERT - EXXONMOBIL - RECORD MANAGEMENT - PART 11
CERT - EXXONMOBIL - RECORD MANAGEMENT - PART 11CERT - EXXONMOBIL - RECORD MANAGEMENT - PART 11
CERT - EXXONMOBIL - RECORD MANAGEMENT - PART 11
 
kalyan-resume
kalyan-resumekalyan-resume
kalyan-resume
 
2009 11 16 Landerd Bedrijfspresentatie Op Internet
2009 11 16 Landerd Bedrijfspresentatie Op Internet2009 11 16 Landerd Bedrijfspresentatie Op Internet
2009 11 16 Landerd Bedrijfspresentatie Op Internet
 
O papel da tutoria no desenvolvimento curricular
O papel da tutoria no desenvolvimento curricularO papel da tutoria no desenvolvimento curricular
O papel da tutoria no desenvolvimento curricular
 
mobility_whtppr_php
mobility_whtppr_phpmobility_whtppr_php
mobility_whtppr_php
 
extending-php
extending-phpextending-php
extending-php
 
The Adbrand Battles Presentation Final Draft
The Adbrand Battles Presentation Final DraftThe Adbrand Battles Presentation Final Draft
The Adbrand Battles Presentation Final Draft
 
Plan for Physical Activity, Sport and Health in Catalonia
Plan for Physical Activity, Sport and Health in CataloniaPlan for Physical Activity, Sport and Health in Catalonia
Plan for Physical Activity, Sport and Health in Catalonia
 
dr_4
dr_4dr_4
dr_4
 
hwk1
hwk1hwk1
hwk1
 
Tributo A The Beatles
Tributo A The BeatlesTributo A The Beatles
Tributo A The Beatles
 
nukesop
nukesopnukesop
nukesop
 
Fall_2008_CS601_W1_Tyngsboro
Fall_2008_CS601_W1_TyngsboroFall_2008_CS601_W1_Tyngsboro
Fall_2008_CS601_W1_Tyngsboro
 

Ähnlich wie newperl5

Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionsUnit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionssana mateen
 
Complete Overview about PERL
Complete Overview about PERLComplete Overview about PERL
Complete Overview about PERLRavi kumar
 
perl course-in-mumbai
 perl course-in-mumbai perl course-in-mumbai
perl course-in-mumbaivibrantuser
 
perl course-in-mumbai
perl course-in-mumbaiperl course-in-mumbai
perl course-in-mumbaivibrantuser
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20Max Kleiner
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Roy Zimmer
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashessana mateen
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionProf. Wim Van Criekinge
 
Tutorial perl programming basic eng ver
Tutorial perl programming basic eng verTutorial perl programming basic eng ver
Tutorial perl programming basic eng verQrembiezs Intruder
 

Ähnlich wie newperl5 (20)

Perl slid
Perl slidPerl slid
Perl slid
 
perltut
perltutperltut
perltut
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
Perl_Part4
Perl_Part4Perl_Part4
Perl_Part4
 
Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionsUnit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressions
 
Complete Overview about PERL
Complete Overview about PERLComplete Overview about PERL
Complete Overview about PERL
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
perl course-in-mumbai
 perl course-in-mumbai perl course-in-mumbai
perl course-in-mumbai
 
perl course-in-mumbai
perl course-in-mumbaiperl course-in-mumbai
perl course-in-mumbai
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashes
 
Theperlreview
TheperlreviewTheperlreview
Theperlreview
 
Perl
PerlPerl
Perl
 
PERL.ppt
PERL.pptPERL.ppt
PERL.ppt
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
 
Introduction to perl_lists
Introduction to perl_listsIntroduction to perl_lists
Introduction to perl_lists
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
Tutorial perl programming basic eng ver
Tutorial perl programming basic eng verTutorial perl programming basic eng ver
Tutorial perl programming basic eng ver
 

Mehr von tutorialsruby

<img src="../i/r_14.png" />
<img src="../i/r_14.png" /><img src="../i/r_14.png" />
<img src="../i/r_14.png" />tutorialsruby
 
TopStyle Help & <b>Tutorial</b>
TopStyle Help & <b>Tutorial</b>TopStyle Help & <b>Tutorial</b>
TopStyle Help & <b>Tutorial</b>tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting <b>...</b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting <b>...</b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting <b>...</b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting <b>...</b>tutorialsruby
 
<img src="../i/r_14.png" />
<img src="../i/r_14.png" /><img src="../i/r_14.png" />
<img src="../i/r_14.png" />tutorialsruby
 
<img src="../i/r_14.png" />
<img src="../i/r_14.png" /><img src="../i/r_14.png" />
<img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 

Mehr von tutorialsruby (20)

<img src="../i/r_14.png" />
<img src="../i/r_14.png" /><img src="../i/r_14.png" />
<img src="../i/r_14.png" />
 
TopStyle Help & <b>Tutorial</b>
TopStyle Help & <b>Tutorial</b>TopStyle Help & <b>Tutorial</b>
TopStyle Help & <b>Tutorial</b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting <b>...</b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting <b>...</b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting <b>...</b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting <b>...</b>
 
<img src="../i/r_14.png" />
<img src="../i/r_14.png" /><img src="../i/r_14.png" />
<img src="../i/r_14.png" />
 
<img src="../i/r_14.png" />
<img src="../i/r_14.png" /><img src="../i/r_14.png" />
<img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Kürzlich hochgeladen

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Kürzlich hochgeladen (20)

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

newperl5

  • 1. Introduction to Perl including Perl 5 Phil Spector Statistical Computing Facility Department of Statistics University of California, Berkeley 1 What is Perl? Practical Extraction and Report Language Developed by Larry Wall in the late 1980s Combines features of awk, sed, grep and shell scripts Originally developed for UNIX; now available widely No inherent limitations to the size of problems it can handle 2
  • 2. Some Typical Uses of Perl NOT for computational algorithms preprocessing input for other programs postprocessing output from other programs repetitive editing, searching or processing of a series of les simpli ed access to system calls managing tasks requiring coordination among programs emerging as a language of choice for WWW CGI scripts prototyping more ambitious projects 3 Accessing Perl Under UNIX, create an executable le whose rst line is ! usr local bin perl optional flags and whose remaining lines contain your perl program Alternatively, invoke perl from the command line: perl optional flags perl program ... Some of the ags available include: -e - invoke perl with a one line program -w - invoke perl in warning mode -n - invoke perl with automatic input loop -d - invoke perl with symbolic debugger Flags can be combined. A useful example is perl -de 0 which will run the debugger with no program. 4
  • 3. Variables All variables begin with a special symbol: $ - scalar @ - array - associative array Each type of variable has its own namespace Variable names are case sensitive: , $var $Var and $VAR are three di erent variables By default, all variables are global Perl determines type numeric or character, scalar or array by context Numbers initialize to 0, characters initialize to Eliminate variables with undef 5 System Variables There are many built-in variables which control the behavior of perl; each of the variables has a terse name, as well as a one or more mnemonic ones. To access the long names in the table below, include the line use English; in your perl program Name Long Name Name Long Name $ $INPUT RECORD SEPARATOR $ $OUTPUT RECORD SEPARATOR $, $OUTPUT FIELD SEPARATOR $. $INPUT LINE NUMBER $ $UID $ $EUID $$ $PROCESS ID $ $MATCH $! $OS ERROR $? $CHILD ERROR $| $OUTPUT AUTOFLUSH $^T $BASETIME $ARGV name of le being read @ARGV array of command line args 6
  • 4. Arrays Regular arrays @ are indexed by number - negative numbers count from the end of the array The highest index of an array can be found using $array By default, indexing of arrays starts at 0 Can be changed with automatic variable $ Associative arrays are indexed by strings Associative arrays use curly braces like $ary $value Subscripting can be used to create scalars or arrays Suppose @T is an array with 10 elements @part = @T 0,1,2 ; array with three elements $part = $T 0 ; scalar More complex structures can be stored in arrays by using references 7 Operators All the standard binary operators from C + - addition - - subtraction - division * - multiplication Additional operators ** - exponentiation . - string concatenation x - string repetition .. - range operator 1..3 1,2,3 All operators have a corresponding assignment operator For example $string .= $add concatenates $string and $add and puts the result into $string Increment and decrement operators ++ - increments -- - decrements pre x before evaluation, post x after evaluation || is logical or, is logical and - These di er from the C operators in that they return the last expression evaluated instead of 0 or 1. You can also use the words or or and. 8
  • 5. Comparison Operators Perl provides two sets of comparison operators, one for numbers and one for strings It's your responsibility to use the right one the -w ag helps Function Numerical Character Equality == eq Non-equality != ne Less than lt Greater than gt Less than or equal = le Greater than or equal = ge Comparison = cmp 9 Quoting Operators While we generally think of quotes as literal values, perl provides operators which provide similar capabilities. These are especially useful if the object to be quoted contains quotes. qftextg - similar to the single quote '. No variable interpolation is performed. qq text - similar to the double quote . Variable f g interpolation is performed qx text - similar to the backquote `. After variable f g interpolation, the text is treated as an operating system command, and its result is returned. qw text - returns an array of words from text, equivalent to f g quoting each one. No interpolation is performed. You can use any character you choose in place of the fg pair. 10
  • 6. Simple Examples Print only lines with exactly ve elds perl -ne 'print if split == 5' filename Print lines that are longer than 80 characters perl -ne 'print if length 80' filename Print the 10th through 20th lines of a le perl -ne 'print if $. = 10 $. = 20' filename Print lines where the third eld is 0 perl -ne 'print if split 2 == 0' filename Change cat to dog perl -pe 's cat dog ' filename Translate lowercase to uppercase perl -pe 'tr a-z A-Z ;' filename 11 Perl Functions 1 Note: Most functions operate on $_ if they have no arguments For more information, type perldoc -f functionname. chop - removes last character of its argument Useful for removing newlines: while chop; ... $_ no longer contains a newline split - break a line into words @T = split; breaks $_ into words, @T = split,; uses comma as separator @w = split , + ,$in; uses comma or space 12
  • 7. Perl Functions 2 join - combine an array or list print join ,@T; $fn = join ,@parts; keys - produce array containing the indices of an associative array @thekeys = keysarray; values - produce ordinary array containing the values of an associative array each - iteratively returns a key value pair from an associative array, or a null value at the end of the array. while$key,$value = eacharray ... iterates over all the key value pairs. 13 Perl Functions 3 index - returns the position of the rst occurence of a substring within a string. returns -1 if no match $str = the cat in the hat; $i = index$str,'cat'; sets $i equal to 4. substr - extracts part of a string from a larger string $piece = substr$str,3,5; 5 chars, start at pos. 3 $part = substr$str,3; from pos. 3 to the end $end = substr$str,-5; starts 5 chars from end grep - evaluate an expression for each element of an array, and return an array of elements for which the expression was true @joes = grep joe ,@array; 14
  • 8. Perl Functions 4 map - returns a list resulting from evaluating an expression on each element of a list. @cts = maplength,@text @cts will contain the lengths of each element of @text. eof - returns 1 if the next input would return end of le. eval - evaluate a string as if it were a Perl program unpack - breaks a string into an array using format codes Can be used for xed format records or binary data @T = unpackx3A4A5,$in; like 3x,a4,a5 @N = unpackd4,$vals; reads 4 doubles binary pack does the opposite of unpack 15 Perl Functions 5 push - add an element to the end of an array push@array,$newval; pop - remove and return the last value of an array $lastvalue = pop@array; shift - remove and return the rst value of an array $firstvalue = shift@array; 16
  • 9. Programming in Perl All statements must end in a semicolon ; Blocks of statements are surrounded by curly braces Control statements from C: for, while, goto Additional statements: unless and until Inside loops, use next and last Compound statements can eliminate the need for brackets Examples: $x = 3 if $a $b; $new = sub$new until $new $old; foreachstatement makes processing arrays easy Example: foreach $value @array ... 17 Reading Input Basic input operator is angle brackets: Perl is clever about guring out where input comes from Reads from les if their names appear on the command line Reads from standard input otherwise open function creates a lehandle openFI,filename || die Couldn't open filename; Then read from filename with $in = FI ; Character based input can be performed using the read and seek functions: readFILEHANDLE,$target,$length; $success = seekFILEHANDLE,$position,$whence; 18
  • 10. Two Special Cases With a while statement, input goes to $_ while or while FILEHANDLE ... each line is read into $_ This is so useful, it's implemented as the -n ag. If a wildcard is in the brackets, it is expanded and $_ set to each lename while *.c openFI,$_; . . . 19 Filehandles Special cases: openFH, filename; open for input only openFH, filename; open for output only openFH, $filevar; same using variable openFH, filename; open for append openPI,command|; open pipe from 'command' openPI,|command; open pipe to 'command' Automatic Filehandles: , , STDIN STDOUT STDERR $response = STDIN ; chop$response; Input record separator de ned by automatic variable $ Setting $ = 0777 causes the whole le to be read into a scalar Reading a lehandle into an array reads the whole le 20
  • 11. References References are a way of storing a link to one variable as the value of another variable, and can be used to produce structures of arbitrary complexity. Perl will never automatically dereference your references you always need to explicitly dereference them. To explicitly make a variable a reference, you can use the backslash operator: $thearray = @array; To dereference a reference, surround the reference name with curly braces , and precede it with the appropriate operator: $value = $ $thearray 2 ; extract a scalar @vals = @ $thearray 2..5 ; extract an array slice You can check to see whether a variable is a reference using the ref function, which returns for a regular variable. 21 References cont'd One of the most useful ways of using references is to create an array of arrays, similar to C's multiply subscripted arrays. In these examples, the arrays are created implicitly. @ $test harry = 5,3,2,9; makes an array print $test harry 3 ; prints 9 $x 1 3 = 17; creates x on the fly When an element of an array is a reference to an array, you must dereference it correctly to use it as an array: push@ $test harry ,17; Double subscripts are shorthand for the - operator: print $test harry 2 ; prints 2 print $test harry - 2 ; same as above 22
  • 12. Example: Rearranging output from rusers The UNIX rusers command lists users on each machine on a network. We'll rearrange the output to give a list of users and the machines to which they are logged in: ! usr local bin perl openRU,rusers `stathosts`|; while RU chop; @T=split' '; $machine = shift@T =~ s .* ..* $1 ; foreach $t @T push@ $usr $t ,$machine if!grep ^$machine$ ,@ $usr $t ; @users = sortkeysusr; foreach $u @users printfsss n,$u,length$u 8 ? t t : t, join ,@ $usr $u ; 23 rusers Example cont'd The rusers output looks like: alpha.Berke joe fred sam beta.Berkel fred fred fred fred harry gamma.Berke sue john sam ... The output from the perl script looks like: fred alpha beta harry beta joe alpha john gamma sam alpha gamma sue gamma ... 24
  • 13. Example: Finding and killing jobs Suppose we want a command which will nd telnet sessions which we have initiated and selectively eliminate them. The UNIX ps command can list the telnet sessions. We could then present the process id to the kill command. We'll use perl to automate the process. ! usr local bin perl @ps = ` usr ucb ps auxww | grep telnet`; foreach $ps @ps @T = split ,$ps; if$T 10 =~ ^telnet printKill session to $T 11 ? ; $resp = STDIN ; chop $resp; kill 15,$T 1 if$resp eq y; 25 Printing Remember that variables are expanded inside of quotes, making many printing tasks simple. print function $, is eld separator $ is record separator printf function behaves like its counterpart in C You can specify a lehandle as an alternative to STDOUT print STDERR Error in input line $. n; Simpli ed printing of errors and warnings warn - prints message with newline to standard error die - like warn, but exits after printing 26
  • 14. More on Printing Use escape characters to literally print special characters $cost = 100; print The cost is $$cost n; results in The cost is $100 Include large blocks of text using perl's here-is syntax: print identifier; text to be printed identifier Extensive formatted printing can be done with format write 27 Sorting The sort function by default performs a lexicographical sort. Alternatively, a subroutine or block of statements can be provided. Plain sort gives lexicographical sort: @snames = sort@names; Using = gives numerical sort note no comma: @svals = sort $a = $b @values; Sorting an associative array based on keys: @skeys = sortkeysarray; foreach $key @skeys push@sarray,$array $key ; Sorting keys based on the values of an associative array: @skeys = sort $array $a = $array $b keysarray; 28
  • 15. Functions which return Arrays You can use a list with individual members instead of an array $first, $last = split ,$name; You can extract just part of a returned array first word from $_ is stored in $first $first = split 0 ; second through fifth words in $line @some = split ,$line 2..5 ; Setting a scalar to an array results in the number of elements $num is number of comma-separated items in $line $num = split,,$line; 29 Examples Finding Unique Lines in a File ! usr bin perl -n -n puts the perl program in a while loop print if$x $_ ++ == 0; Finding the Longest Line in a File ! usr bin perl -n chop; remove the newline $ll = length; $maxl = $ll if $ll $maxl; print $maxl n if eof; 30
  • 16. Example: Keeping Track of Number of Fields ! usr bin perl while $n = split; $ct $n ++; @skey = sort $a = $b keysct; foreach $key @skey print $key: t$ct $key n; 31 Regular Expressions =~ operator allows testing or substitution $in =~ m r e returns 1 if r e is in $in $in !~ m r e returns 1 if r e is not in $in The m is optional; you could use r e instead. $str =~ s old new ; changes old to new in $str $new = $save =~ s old new ; doesn't change$save Variables are expanded inside of regular expressions Regular expressions can be arguments to split or to set $ Note: With the m ... or s ... operators, you can replace the with any character you choose, or you can use pairs of or fg as delimiters. Avoid using ? as a delimiter. 32
  • 17. Constructing Regular Expressions Regular Expressions can contain any combination of: Literal Characters Note: Always escape . ^ $ + ? * | Character Classes Characters surrounded by square brackets Negated Character Classes First character in brackets is a caret ^ Escape Characters n newline f formfeed t tab b word boundary d digit w alphanumeric B non-boundary D non-digit W non-alphanumeric Octal or Hexadecimal Characters nnn - octal xnn - hexadecimal - Represents a backspace in a character class 33 Constructing Regular Expressionscont'd Operators within Regular Expressions ^ anchors expression to beginning of target $ anchors expression to end of target . matches any single character except newline | separates alternative patterns groups patterns together * matches 0 or more occurrences of preceding entity ? matches 0 or 1 occurrences of preceding entity + matches 1 or more occurrences of preceding entity n matches exactly n occurrences of preceding entity n, matches at least n occurrences of preceding entity n,m matches between n and m occurrences 34
  • 18. Grouping in Regular Expressions In addition to grouping alternations, parentheses are used in regular expressions to tag sub-expressions which can be referred to later. The expression contained by the i-th set of parentheses counting from the left is referred to as i on the left-hand side of a substitution, and $i anywhere else. If you want to use parentheses for just grouping, without tagging the enclosed sub-expression, use ?: and for grouping. For example, the following program identi es the rst occurrence in each line of input of two identical words in a row: if b w+ + 1 b print '$1 appears twice in line $. n'; Note that the tagged expression is referred to as 1 in the regular expression itself, but as $1 outside the regular expression. 35 Modi ers for Regular Expressions A number of letters can be placed after the nal delimiter of a regular expression to modify some aspects of the matching process i - Makes the match case-insensitive. g - Operates on all occurences of the regular expression, instead of just the rst, which is the default behavior. s - Allows . to match newline along with everything else m - Changes the meaning of ^ and $ anchors so they are meaningful for each logical line. You can always use A and Z to mean the beginning and end of the input. e - Treats the right hand side of the s ... ... operator as a Perl expression instead of simply text. x - Ignore whitespace and comments inside of the regular expression - useful for formatting complex regular expressions. 36
  • 19. Return Values from Regular Expression Operators The values returned from the m ... and s ... ... operators are di erent depending on the context in which they are used m ... operator When used as a scalar, returns 1 if the match was successful, 0 otherwise When used as an array, returns a list of tagged items. m ... g operator When used as an array, returns a list of tagged items corresponding to as many matches as were found. s ... ... operator In scalar or array context, returns the number of substitutions which actually took place. 37 Examples of Regular Expressions 1 Change NA to . period s NA . Problem: NAME gets changed to .ME Solution: Use b to specify word boundaries s bNA b . The s command returns a count of the number of substitutions which are carried out, so it can be used to count occurrences of regular expressions: while $i = s bNA b . g; print Too many missing in line $. n if $i 5; 38
  • 20. Examples of Regular Expressions 2 Reverse the order of two words s w+ w+ $2 $1 ; $line = one two three four; $line =~ s w+ w+ $2 $1 ; two one three four $line =~ s w+ w+ $2 $1 g; two one four three Find a word followed by a number if w+ d+ print word is $1, number is $2 n; Note that $1 and $2 retain their values after the regular expression. 39 Examples of Regular Expressions 3 Add one to a series of line numbers at the beginning of each line. s ^ d+ $1 + 1 e; Since we can't add 1 to a number using text, the e modi er was used. Function calls which return appropriate types can also be used with the e modi er. For example, to convert numbers to their hexadecimal representation, you could use the sprintf function: $str = 125 234 321; $str =~ s d+ sprintfx,$1 ge; 7d ea 141 40
  • 21. Greediness of Regular Expressions Consider extracting URLs from a document. One strategy could be to nd strings which start with http or ftp, followed by a colon : and which end with a character which is not a valid character for a URL, leading to a pattern like ?:http|ftp:.* ^-_ .~ w But if we use this pattern on text such as Go to http: www.info.com and report any problems. we would nd that $1 will be set to http: www.info.com and report any problems. since the end of line allowed a longer match than the address alone. 41 Greediness of Regular Expressions cont'd One way to solve the problem is to replace the occurence of ., which represents any character, with a more speci c character class. In this case, we could use any character which is a valid part of a URL: ?:http|ftp: -_ .~ w * ^-_ .~ w A more general approach is to use a question mark ? after the quanti er to tell perl to nd the smallest string that matches instead of the longest, which is the default: ?:http|ftp:.*? ^-_ .~ w Either of these approaches will extract only the URL and not the text which follows. 42
  • 22. Iterative Use of the m ... g operator When used inside a while loop, the m ... g operator can be used to process multiple occurences of regular expressions. For example, suppose we wanted to process a le containing email addresses, in order to count how many address were in each domain. Recall email addresses are in the form username@domain.name. The following program would process each address, even if there were multiple addresses on the line: while chop; while b w+@ ^@ + g $count $2 ++; foreach $key keyscount print $count $key addresses from $key n, 43 More Examples of Regular Expressions Remove trailing newline alternative to chop s n$ ; Eliminate leading 0s in a line of numbers s b0+ d $1 g; Removing the leading portion of a pathname $tail = $path =~ s.+ .*$1; Capitalize the rst letter of rst word in a line s ^ a-z U$1 E ; Remove comments from a line $line =~ s .*.* $1 ; 44
  • 23. Using Perl to Edit Multiple Files Two ags are especially useful when using perl as a stream editor: -p sets up input loop and automatically prints $_ -i allows inplace editing an extension backup copy For example, perl -pe 's bNA b . g' old.dat new.dat would change all NAs to periods in old.dat, and write to new.dat perl -i.bak -pe 's bNA b . g' *.dat would do the same in place for all les ending with .dat, creating copies with .bak appended to the names. This command works well with the UNIX find command: perl -i.bak -pe 'sINCL=-I..INCL=-I.. -I.. include' `find . -name Makefile -print` 45 Interacting with the Operating System system lets you execute an operating system command backquotes ` ` or the qx operator let you capture output fg into a perl variable retains newlines multiline output can be captured in an array variable expansion takes place inside of backquotes Perl provides functions for many operating system calls chdir, kill, sleep, wait, exec, fork, unlink, mkdir, etc. The associative array ENV contains environmental variables $ENV USER , $ENV EDITOR , etc. 46
  • 24. File System Operators As in many shells, perl o ers operators for simpli ed le queries Op Tests Op Tests Op Tests -r Readable -w Writable -x Executable -l Link -e Existence -f Plain File -d Directory -T Text -B Binary Example: $prefix = usr local help ; $filename = $prefix.$topic; warnNo help file for $topic unless -f $filename; 47 Example: Executing Commands on a Network ! usr local bin perl @machines = winnie,pooh,kestrel,eeyore; foreach $machine @machines $job = `rsh $machine ps aux | grep $ARGV 0 `; print Jobs on $machine: n$job n if$job; 48
  • 25. Formatted Output The format statement allows you to de ne a template for output produced by the write function. Substitutions are made as follows: @ left justify as many columns as there are s @ right justify as many columns as there are s @||| center as many columns as there are |s Specify the variables to be printed below the format lines, separated by commas Final line of the format should have a single period You can specify a header to appear on top of each page $= is the page size 49 Example of Format Statement format STDOUT_TOP = Name Office Extension . format STDOUT = @ @ @ $name,$office,$ext . while $name,$office,$ext = split,; write; 50
  • 26. Example of Format Statement cont'd The previous example would convert Fred Smith,425,x7743 John Jones,372,x4450 Harold Johnston,421,x4622 to: Name Office Extension Fred Smith 425 x7743 John Jones 372 x4450 Harold Johnston 421 x4622 51 Creating Subroutines De ne a subroutine using sub subroutine name statements The last expression evaluated is returned, or use return Arguments to subroutines are passed as one list through @_ : First arg is $_ 0 , second is $_ 1 , etc. Arguments other than scalars must be passed to subroutines as references Recall by default perl variables are global. The my function can create local variables within the subroutine. Perl subroutines may be recursive 52
  • 27. Using Subroutines Call with subargs... Note that parentheses and arguments are optional Include subroutines using the require statement require 'file.pl'; The require statement searches the directories in @INC, which will always contain the current directory. To read in a subroutine using require, the last line must be 1; 53 Example: Prompting for a Password sub getpass my$prompt = $_ 0 ? Password: : $_ 0 ; systemstty -echo; printSTDERR $prompt; $pass = STDIN ; systemstty echo; chop$pass; printfSTDERR n; return $pass; 1; If the subroutine was in a le called getpass.pl, use: require 'getpass.pl'; $secret = getpass; or getpassPrompt:; 54
  • 28. Example: Counting Strings in Files Suppose we wish to write a subroutine which will accept a list of les as its rst argument, a regular expression as its second argument, and which will return an array containing the number of times the regular expression occurs in each of the les. Since arguments to perl subroutines are passed as a single list, the rst argument must be a reference to a list. In the subroutine on the next slide, the list will be stored in a local array called files through the use of the my function. To call a subroutine such as this, a reference must be passed as the rst argument, for example @myfiles = test.1,data,README; @cts = countpat @myfiles,duck; 55 Example: Counting Strings in Files cont'd sub countpat my@files = @ $_ 0 ; my$pat = $_ 1 ; my@res = ; foreach $f @files openFI, $f || die Couldn't open $f; $ct = 0; while FI $ct++ while s $pat ; closeFI; push@res,$ct; return@res; 56
  • 29. Example: Resolving Links recursion On many systems there are long chains of links, so using ls to nd where a le really is can be confusing. Since perl functions can be called recursively, they provide a simple solution. The strategy is to write a function which prints a given lename, and, if it is a link, to follow the ls convention of using - to point to the link. This process is continued until a le which is not a link is found. Since many links are stored as absolute pathnames, we'll need a function which takes a relative pathname and makes it absolute. That turns out to be the hard part. The main loop and printing program reslink are shown on the next slide; the pathname resolution program resdir is on the slide after the next. 57 Example: Resolving Links cont'd main loop foreach $name @ARGV reslink$name; printf n; resolve links using - notation sub reslink printfs,$_ 0 ; if! -e $_ 0 printfdoes not exist if-l $_ 0 printf - ; reslinkresdir$_ 0 ; 58
  • 30. Example: Resolving Links cont'd sub resdir my $dir = $_ 0 ; my $now = readlink$dir; ifsubstr$now,0,1 ne not absolute pathname $i = 1; @n = split ,$dir; resolve relative links .. ifindex$now,.. -1 $i++ while $now =~ s . . ; $now = join ,@n 0..$n-$i ,$now; return $now; 59 Command Line Arguments Arguments are stored in the array @ARGV First argument is $ARGV 0 , second is $ARGV 1 , etc. Getopts subroutine Argument to Getopts is a string of characters Options with arguments are followed by : in the string Variables of the form $opt_letter are set appropriately Options and arguments are removed from @ARGV require 'getopts.pl'; Getoptsan:x; Running program -a -n 100 will set $opt_a to 1, $opt_n to 100, and $opt_x to 60
  • 31. Resources Manual page man perl - provides a overview of the other 25 ! manual pages describing perl Books: Note: 2nd edition is perl5, 1st edition is perl4 Learning Perl, 2nd Edition by Randal L. Schwartz Programming Perl, 2nd Edition by Larry Wall Randal L. Schwartz Perl Cookbook by Tom Christiansen Nathan Torkington all three published by O'Reilly and Associates Internet Newsgroup: comp.lang.perl FAQ from convex.com pub perl info faq anon. ftp Reference Card part of Programming Perl from CPAN archive doc perlref-5.004.1.tar.gz 61 Resourcescont'd Source is available from CPAN archives try www.perl.org or check http: language.perl.com CPAN for more information. The o cial perl website maintained by Tom Christiansen is located at http: www.perl.com . http: www.eecs.nwu.edu perl perl.html is another good starting point for nding WWW perl resources. 62