home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / languages / perl / tutorial / slides / ascii next >
Encoding:
Text File  |  1990-03-10  |  23.2 KB  |  1,028 lines

  1.  
  2.  
  3.                               PERL
  4.  
  5.  
  6.                     a language by Larry Wall
  7.  
  8.  
  9.             Practical Extraction and Report Language
  10.  
  11.  
  12.                                or
  13.  
  14.  
  15.              Pathologically Eclectic Rubbish Lister
  16.  
  17.  
  18.                         Tom Christiansen
  19.                    CONVEX Computer Corporation
  20.  
  21.  
  22.                 ---------------------------------------
  23.  
  24.                             Overview
  25.  
  26.  
  27.    o What is Perl: features, where to get it, preview
  28.  
  29.  
  30.    o Data Types: scalars and arrays
  31.  
  32.  
  33.    o Operators
  34.  
  35.  
  36.    o Flow Control
  37.  
  38.  
  39.    o Regular Expressions
  40.  
  41.  
  42.    o I/O: regular I/O, system functions, directory  access,  for-
  43.      matted I/O
  44.  
  45.  
  46.    o Functions and Subroutines: built-in array and  string  func-
  47.  
  48.      tions
  49.  
  50.  
  51.    o Esoterica: suid scripts, debugging, packages,  command  line
  52.      options
  53.  
  54.  
  55.    o Examples
  56.  
  57.  
  58.                      ---------------------------------------
  59.  
  60.                           What is Perl?
  61.  
  62.  
  63.    o An interpreted language that looks a lot like C with  built-
  64.      in  sed,  awk,  and sh, as well as bits of csh, Pascal, FOR-
  65.  
  66.      TRAN, BASIC-PLUS thrown in.
  67.  
  68.  
  69.    o Highly optimized for manipulating printable text,  but  also
  70.      able to handle binary data.
  71.  
  72.  
  73.    o Especially suitable for system management tasks due  to  in-
  74.  
  75.      terfaces to most common system calls.
  76.  
  77.  
  78.    o Rich enough for most general programming tasks.
  79.  
  80.  
  81.    o "A shell for C programmers." [Larry Wall]
  82.  
  83.                      ---------------------------------------
  84.  
  85.                             Features
  86.  
  87.  
  88.    o Easy to learn because much derives from existing tools.
  89.  
  90.  
  91.    o More rapid program development because it's an interpreter
  92.  
  93.  
  94.    o Faster execution than shell script equivalents.
  95.  
  96.  
  97.    o More powerful than sed, awk, or sh; a2p and s2p  translators
  98.      supplied for your old scripts.
  99.  
  100.  
  101.    o Portable across many different architectures.
  102.  
  103.  
  104.    o Absence of arbitrary limits like string length.
  105.  
  106.  
  107.    o Fits nicely into UNIX tool and filter philosophy.
  108.  
  109.  
  110.    o It's free!
  111.  
  112.  
  113.                      ---------------------------------------
  114.  
  115.                          Where to get it
  116.  
  117.  
  118.    o Any comp.sources.unix archive
  119.  
  120.  
  121.    o Famous archive servers
  122.         o uunet.uu.net    192.48.96.2
  123.  
  124.         o tut.cis.ohio-state.edu  128.146.8.60
  125.  
  126.  
  127.    o Its author, Larry Wall <lwall@jpl-devvax.jpl.nasa.gov>
  128.         o jpl-devvax.jpl.nasa.gov 128.149.1.143
  129.  
  130.  
  131.    o Perl reference guide (in  postscript  form)  also  available
  132.  
  133.      from Ohio State, along with some sample scripts and archives
  134.      of the perl-users mailing list.
  135.  
  136.  
  137.    o USENET newsgroup comp.lang.perl good source  for  questions,
  138.  
  139.      comments, examples.
  140.  
  141.                      ---------------------------------------
  142.  
  143.                              Preview
  144.  
  145.  
  146.    o It's not for nothing  that  perl  is  sometimes  called  the
  147.      "pathologically  eclectic rubbish lister."  Before you drown
  148.  
  149.      in a deluge of features, here's a  simple  example  to  whet
  150.      your  appetites  that demonstrates the principal features of
  151.  
  152.      the language, all of which have been present  since  version
  153.      1.
  154.  
  155.  
  156.         while (<>) {
  157.  
  158.             next if /^#/;
  159.             ($x, $y, $z) = /(\S+)\s+(\d\d\d)\s+(foo|bar)/;
  160.  
  161.             $x =~ tr/a-z/A-Z/;
  162.             $seen{$x}++;
  163.  
  164.             $z =~ s/foo/fear/ && $scared++;
  165.             printf "%s %08x %-10s\n", $z, $y, $x
  166.  
  167.                 if $seen{$x} > $y;
  168.         }
  169.  
  170.  
  171.                      ---------------------------------------
  172.  
  173.                            Data Types
  174.  
  175.  
  176.    o Basic data types are scalars, indexed arrays of scalars, and
  177.      associative arrays of scalars.
  178.  
  179.  
  180.    o Scalars themselves are either string, numeric,  or  boolean,
  181.  
  182.      depending  on  context.   Values  of  0  (zero) and '' (null
  183.      string) are false; all else is true.
  184.  
  185.  
  186.    o Type of variable determined by leading special character.
  187.  
  188.         o $       scalar
  189.         o @       indexed array (lists)
  190.  
  191.         o %       associative array
  192.         o &       function
  193.  
  194.  
  195.    o All data types have their own separate namespaces, as do la-
  196.  
  197.      bels, functions, and file and directory handles.
  198.  
  199.                      ---------------------------------------
  200.  
  201.                       Data Types (scalars)
  202.  
  203.  
  204.    o Use a $ to indicate a scalar value
  205.  
  206.  
  207.         $foo = 3.14159;
  208.  
  209.  
  210.         $foo = 'red';
  211.  
  212.  
  213.         $foo = "was $foo before";       # interpolate variable
  214.  
  215.  
  216.         $host = `hostname`;     # note backticks
  217.  
  218.  
  219.         ($foo, $bar, $glarch) = ('red', 'blue', 'green');
  220.  
  221.  
  222.         ($foo, $bar) = ($bar, $foo); # exchange
  223.  
  224.                      ---------------------------------------
  225.  
  226.                     Special Scalar Variables
  227.  
  228.  
  229.    o Special scalars are named with punctuation (except $0).  Ex-
  230.      amples are
  231.  
  232.  
  233.         o $0      name of the currently executing script
  234.  
  235.         o $_      default for pattern operators and implicit I/O
  236.         o $$      the current pid
  237.  
  238.         o $!      the current system error message from errno
  239.         o $?      status of last `backtick`, pipe, or system
  240.  
  241.         o $|      whether output is buffered
  242.         o $.      the current line number of last input
  243.  
  244.         o $[      array base, 0 by default; awk uses 1
  245.         o $<      the real uid of the process
  246.  
  247.         o $(      the real gid of the process
  248.         o $>      the effective uid of the process
  249.  
  250.         o $)      the effective gid of the process
  251.  
  252.                           ---------------------------------------
  253.  
  254.                        Data types (arrays)
  255.  
  256.  
  257.    o Indexed arrays (lists); $ for one scalar element, @ for all
  258.         $foo[$i+2] = 3; # set one element to 3
  259.  
  260.         @foo = ( 1, 3, 5 );# init whole array
  261.         @foo = ( ) ;    # initialize empty array
  262.  
  263.         @foo = @bar;    # copy whole @array
  264.         @foo = @bar[$i..$i+5];  # copy slice of @array
  265.  
  266.  
  267.    o $#ARRAY is index of highest subscript, so the script's  name
  268.  
  269.      is   $0   and   its  arguments  run  from  $ARGV[0]  through
  270.      $ARGV[$#ARGV], inclusive.
  271.  
  272.  
  273.    o Associative (hashed) arrays; $ for one scalar element, % for
  274.  
  275.      all
  276.         $frogs{'green'} += 23;  # 23 more green frogs
  277.  
  278.         $location{$x, $y, $z} = 'troll'; # multi-dim array
  279.         %foo = %bar;            # copy whole %array
  280.  
  281.         @frogs{'green', 'blue', 'yellow'} = (3, 6, 9);
  282.  
  283.                      ---------------------------------------
  284.  
  285.                      Special Array Variables
  286.  
  287.  
  288.    o @ARGV   command line arguments
  289.  
  290.  
  291.    o @INC    search path for files called with do
  292.  
  293.  
  294.    o @_      default for split and subroutine parameters
  295.  
  296.  
  297.    o %ENV    the current enviroment; e.g. $ENV{'HOME'}
  298.  
  299.  
  300.    o %SIG    used to set signal handlers
  301.  
  302.  
  303.         sub trapped {
  304.             print STDERR "Interrupted\007\n";
  305.  
  306.             exit 1;
  307.         }
  308.  
  309.         $SIG{'INT'} = 'trapped';
  310.  
  311.                      ---------------------------------------
  312.  
  313.                             Operators
  314.  
  315.  
  316. Perl uses all of C's operators except for type  casting  and  `&'
  317. and `*' as address operators, plus these
  318.  
  319.  
  320.    o exponentiation:  **, **=
  321.  
  322.  
  323.    o range operator: ..
  324.  
  325.         $inheader = 1 if /^From / .. /^$/;
  326.         if (1..10) { do foo(); }
  327.  
  328.         for $i (60..75) { do foo($i); }
  329.         @new = @old[30..50];
  330.  
  331.  
  332.    o string concatenation: ., .=
  333.  
  334.  
  335.         $x = $y . &frob(@list) . $z;
  336.  
  337.         $x .= "\n";
  338.  
  339.                      ---------------------------------------
  340.  
  341.                       Operators (continued)
  342.  
  343.  
  344.    o string repetition: x, x=
  345.  
  346.  
  347.         $bar = '-' x 72; # row of 72 dashes
  348.  
  349.  
  350.    o string tests: eq, ne, lt, gt, le, ge
  351.  
  352.  
  353.         if ($x eq 'foo') { }
  354.         if ($x ge 'red' ) { }
  355.  
  356.  
  357.    o file test operators like augmented /bin/test tests  work  on
  358.  
  359.      strings or filehandles
  360.  
  361.  
  362.         if (-e $file)  { } # file exists
  363.         if (-z $file) { } # zero length
  364.  
  365.         if (-O LOG) { }    # LOG owned by real uid
  366.         die "$file not a text file" unless -T $file;
  367.  
  368.  
  369.                      ---------------------------------------
  370.  
  371.                           Flow Control
  372.  
  373.  
  374.    o Unlike C, blocks always require enclosing braces {}
  375.  
  376.  
  377.    o unless and until are just if and while negated
  378.  
  379.  
  380.         o if (EXPR) BLOCK else BLOCK
  381.         o if (EXPR) BLOCK elsif (EXPR) BLOCK else BLOCK
  382.  
  383.         o while (EXPR) BLOCK
  384.         o do BLOCK while EXPR
  385.  
  386.         o for (EXPR; EXPR; EXPR) BLOCK
  387.         o foreach $VAR (LIST) BLOCK
  388.  
  389.  
  390.    o For readability, if, unless, while, and until may be used as
  391.  
  392.      trailing statement modifiers as in BASIC-PLUS
  393.  
  394.  
  395.         return -1 unless $x > 0;
  396.  
  397.                      ---------------------------------------
  398.  
  399.                     Flow Control (continued)
  400.  
  401.  
  402.    o Use next and last rather than C's continue and break
  403.  
  404.  
  405.    o redo restarts the current iteration, ignoring the loop test
  406.  
  407.  
  408.    o Blocks (and next, last, and redo) take optional  labels  for
  409.      clearer loop control, avoiding the use of goto to exit nest-
  410.  
  411.      ed loops.
  412.  
  413.  
  414.    o No switch statement, but it's easy to roll your own
  415.  
  416.  
  417.    o do takes 3 forms
  418.         o execute a block
  419.  
  420.           do { $x += $a[$i++] } until $i > $j;
  421.         o execute a subroutine
  422.  
  423.           do foo($x, $y);
  424.         o execute a file in current context
  425.  
  426.           do 'subroutines.pl';
  427.  
  428.                           ---------------------------------------
  429.  
  430.                        Regular Expressions
  431.  
  432.  
  433.    o Understands egrep regexps, plus
  434.  
  435.  
  436.         o \w, \W  alphanumerics plus _ (and negation)
  437.         o \d, \D  digits (and negation)
  438.  
  439.         o \s, \S  white space (and negation)
  440.         o \b, \B  word boundaries (and negation)
  441.  
  442.  
  443.    o C-style escapes recognized, like \t, \n, \034
  444.  
  445.  
  446.    o Don't  escape  these  characters  for  their  special  mean-
  447.  
  448.      ing:  ( ) | { } +
  449.  
  450.  
  451.    o Character classes may contain metas, e.g. [\w.$]
  452.  
  453.  
  454.    o Special variables: $& means all text matched, $` is text be-
  455.      fore match, $' is text after match.
  456.  
  457.  
  458.                      ---------------------------------------
  459.  
  460.                  Regular Expressions (continued)
  461.  
  462.  
  463.    o Use \1 .. \9 within rexprs; $1 .. $9 outside
  464.  
  465.  
  466.         if (/^this (red|blue|green) (bat|ball) is \1/)
  467.             { ($color, $object) = ($1, $2); }
  468.  
  469.         ($color, $object) =
  470.             /^this (red|blue|green) (bat|ball) is \1/;
  471.  
  472.  
  473.    o Substitute and translation operators are like sed's s and y.
  474.  
  475.         s/alpha/beta/;
  476.         s/(.)\1/$1/g;
  477.  
  478.         y/A-Z/a-z/;
  479.  
  480.  
  481.    o Use =~ and !~ to match against variables
  482.  
  483.  
  484.         if ($foo !~ /^\w+$/) { exit 1; }
  485.         $foo =~ s/\btexas\b/TX/i;
  486.  
  487.  
  488.                      ---------------------------------------
  489.  
  490.                                I/O
  491.  
  492.  
  493.    o Filehandles have their own distinct namespaces, but are typ-
  494.      ically  all upper case for clarity.  Pre-defined filehandles
  495.  
  496.      are STDIN, STDOUT, STDERR.
  497.  
  498.  
  499.    o Mentioning a filehandle in angle brackets reads next line in
  500.      scalar  context, all lines in an array context; newlines are
  501.  
  502.      left intact.
  503.  
  504.  
  505.         $line = <TEMP>;
  506.         @lines = <TEMP>;
  507.  
  508.  
  509.    o <> means all files supplied on command  line  (or  STDIN  if
  510.  
  511.      none). When used this way, $ARGV is the current filename.
  512.  
  513.  
  514.    o When used in a while construct, input lines are automatical-
  515.      ly assigned to the $_ variable.
  516.  
  517.  
  518.                      ---------------------------------------
  519.  
  520.                          I/O (continued)
  521.  
  522.  
  523.    o Usually iterate over file a line at a time, assigning to  $_
  524.      each time and using that as the default operand.
  525.  
  526.  
  527.         while ( <> ) {
  528.  
  529.             next if /^#/;       # skip comments
  530.             s/left/right/g;     # global substitute
  531.  
  532.             print;              # print $_
  533.         }
  534.  
  535.  
  536.    o If not using the pseudo-file <>, open a filehandle:
  537.  
  538.  
  539.         open (PWD,      "/etc/passwd");
  540.  
  541.         open (TMP,      ">/tmp/foobar.$$");
  542.         open (LOG,      ">>logfile");
  543.  
  544.         open (TOPIPE,   "| lpr");
  545.         open (FROMPIPE, "/usr/etc/netstat -a |");
  546.  
  547.  
  548.                      ---------------------------------------
  549.  
  550.                          I/O (continued)
  551.  
  552.  
  553.    o May also use getc for character I/O and read for raw I/O
  554.  
  555.  
  556.    o Access to eof, seek, close, flock, ioctl, fcntl, and  select
  557.      calls for use with filehandles.
  558.  
  559.  
  560.    o Access to mkdir, rmdir, chmod, chown, link, symlink (if sup-
  561.  
  562.      ported), stat, rename, unlink calls for use with filenames.
  563.  
  564.  
  565.    o Pass printf a filehandle as its first argument unless print-
  566.      ing to STDOUT
  567.  
  568.  
  569.         printf LOG "%-8s %s: weird bits: %08x\n",
  570.  
  571.             $program, &ctime, $bits;
  572.  
  573.  
  574.    o Associative arrays may be bound to dbm files with dbmopen()
  575.  
  576.                      ---------------------------------------
  577.  
  578.                         System Functions
  579.  
  580.  
  581. A plethora of functions  from  the  C  library  are  provided  as
  582. built-ins, including most system calls.  These include
  583.  
  584.  
  585.    o chdir, chroot, exec, exit, fork, getlogin, getpgrp, getppid,
  586.  
  587.      kill,  setpgrp,  setpriority, sleep, syscall, system, times,
  588.      umask, wait.
  589.  
  590.  
  591.    o If your system has Berkeley-style networking, bind, connect,
  592.  
  593.      send,  getsockname,  getsockopt,  getpeername, recv, listen,
  594.      socket, socketpair.
  595.  
  596.  
  597.    o getpw*, getgr*, gethost*, getnet*, getserv*, and getproto*.
  598.  
  599.  
  600.    o pack and unpack can be used for manipulating binary data.
  601.  
  602.  
  603.                   ---------------------------------------
  604.  
  605.                         Directory Access
  606.  
  607.  
  608. Three methods of accessing directories are provided.
  609.  
  610.  
  611.    o You may open a pipe from /bin/ls like this:
  612.         open(FILES,"/bin/ls *.c |");
  613.  
  614.         while ($file = <FILES>) { chop($file); ... }
  615.  
  616.  
  617.    o The directory-reading routines are provided as built-ins and
  618.      operate  on directory handles.  Supported routines are open-
  619.  
  620.      dir, readdir, closedir, seekdir, telldir, and rewinddir.
  621.  
  622.  
  623.    o The easiest way is to use perl's file globbing notation.   A
  624.      string  enclosed  in  angle  brackets containing shell meta-
  625.  
  626.      characters evaluates to a list of matching filenames.
  627.  
  628.  
  629.         foreach $x ( <*.[ch]> ) { rename($x, "$x.old"); }
  630.         chmod 0644, <*.c>;
  631.  
  632.  
  633.                      ---------------------------------------
  634.  
  635.                            Subroutines
  636.  
  637.  
  638.    o Subroutines called either with `do' operator  or  with  `&'.
  639.      Any  of  the  three  principal  data  types may be passed as
  640.  
  641.      parameters or used as a return value.
  642.  
  643.  
  644.         do foo(1.43);
  645.  
  646.  
  647.         do foo(@list)
  648.  
  649.  
  650.         $x = &foo('red', 3, @others);
  651.  
  652.  
  653.         @list = &foo(@olist);
  654.  
  655.  
  656.         %foo = &foo($foo, @foo);
  657.  
  658.                      ---------------------------------------
  659.  
  660.                      Subroutines (continued)
  661.  
  662.  
  663.    o Parameters are received by the subroutine in the special ar-
  664.      ray @_.  If desired, these can be copied to local variables.
  665.  
  666.      This is especially useful for recursive subroutines.
  667.  
  668.  
  669.         $result = &simple($alpha, $beta, @tutti);
  670.         sub simple {
  671.  
  672.             local($x, $y, @rest) = @_;
  673.             local($sum, %seen);
  674.  
  675.             return $sum;
  676.         }
  677.  
  678.  
  679.    o Subroutines may also be called indirectly
  680.  
  681.  
  682.         $foo = 'some_routine';
  683.  
  684.         do $foo(@list)
  685.         ($x, $y, $z) = do $foo(%maps);
  686.  
  687.  
  688.                      ---------------------------------------
  689.  
  690.                           Formatted I/O
  691.  
  692.  
  693.    o Besides printf, formatted I/O can be done  with  format  and
  694.      write statements.
  695.  
  696.  
  697.    o Automatic pagination and printing of headers.
  698.  
  699.  
  700.    o Picture description facilitates lining up multi-line output
  701.  
  702.  
  703.    o Fields in picture may be left or right-justified or centered
  704.  
  705.  
  706.    o Multi-line text-block filling is  provided,  something  like
  707.  
  708.      having a %s format string with a built-in pipe to fmt)
  709.  
  710.  
  711.    o These special scalar variables are useful:
  712.         o $% for current page number,
  713.  
  714.         o $= for current page length (default 60)
  715.         o $- for lines left on page
  716.  
  717.  
  718.                           ---------------------------------------
  719.  
  720.                      Formatted I/O (example)
  721.  
  722. # a report from a bug report form; taken from perl man page
  723. format top =
  724.                         Bug Reports
  725. @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  726. $system,                      $%,         $date
  727. ------------------------------------------------------------------
  728. .
  729.  
  730. format STDOUT =
  731. Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  732.          $subject
  733. Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  734.        $index,                       $description
  735. Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  736.           $priority,        $date,   $description
  737. From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  738.       $from,                         $description
  739. Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  740.              $programmer,            $description
  741. ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  742.                                      $description
  743. ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  744.                                      $description
  745. ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  746.                                      $description
  747. .
  748.  
  749.  
  750.                 ---------------------------------------
  751.  
  752.                     Built-in Array Functions
  753.  
  754.  
  755.    o Indexed arrays function as lists; you can add  items  to  or
  756.      remove them from either end using these functions:
  757.  
  758.         o pop     remove last value from end of array
  759.         o push    add values to end of array
  760.  
  761.         o shift   remove first value from front of array
  762.         o unshift add values to front of array
  763.  
  764.  
  765. For example
  766.  
  767.  
  768.      push(@list, $bar);
  769.  
  770.      push(@list, @rest);
  771.      $tos = pop(@list);
  772.  
  773.      while ( $arg = shift(@ARGV) )  { }
  774.      unshift( @ARGV, 'zeroth arg', 'first arg');
  775.  
  776.  
  777.                   ---------------------------------------
  778.  
  779.             Built-in Array Functions (split and join)
  780.  
  781.  
  782.    o split breaks up a string into an array of new strings.   You
  783.      can split on arbitrary regular expressions, limit the number
  784.  
  785.      of fields you split into, and save  the  delimiters  if  you
  786.      want.
  787.  
  788.  
  789.         @list = split(/[, \t]+/, $expr);
  790.  
  791.         while (<PASSWD>) {
  792.             ($login, $passwd, $uid, $gid, $gcos,
  793.  
  794.                 $home, $shell) = split(/:/);
  795.         }
  796.  
  797.  
  798.    o The inverse of split is join.
  799.  
  800.  
  801.         $line = join(':', $login, $passwd, $uid,
  802.  
  803.                           $gid, $gcos, $home, $shell);
  804.  
  805.                      ---------------------------------------
  806.  
  807.          Built-in Array Functions (sort, grep, reverse)
  808.  
  809.  
  810.    o reverse inverts a list.
  811.  
  812.  
  813.         foreach $tick (reverse 0..10) { }
  814.  
  815.  
  816.    o sort returns a new array with the elements ordered according
  817.      to  their  ASCII values.  Use your own routine for different
  818.  
  819.      collating.
  820.  
  821.  
  822.         print sort @list;
  823.         sub numerically { $a - $b; }
  824.  
  825.         print sort numerically @list;
  826.  
  827.  
  828.    o grep returns a new list consisting of all the  elements  for
  829.      which  a  given  expression is true.  For example, this will
  830.  
  831.      delete all lines with leading pound signs:
  832.  
  833.  
  834.         @lines = grep(!/^#/, @lines);
  835.  
  836.                      ---------------------------------------
  837.  
  838.                Built-in Array Functions (%arrays)
  839.  
  840.  
  841. For manipulating associative arrays, the keys  and  values  func-
  842. tions  return  indexed  arrays  of  the  indices  and data values
  843.  
  844. respectively.  each is used to iterate through an associative ar-
  845. ray to retrieve one ($key,$value) pair at a time.
  846.  
  847.  
  848.    while (($key,$value) = each %array) {
  849.  
  850.        printf "%s is %s\n", $key, $value;
  851.    }
  852.  
  853.  
  854.    foreach $key (keys %array) {
  855.  
  856.        printf "%s is %s\n", $key, $array{$key};
  857.    }
  858.  
  859.  
  860.    print reverse sort values %array;
  861.  
  862.  
  863.                 ---------------------------------------
  864.  
  865.                         String functions
  866.  
  867.  
  868.    o Besides the powerful regular  expression  features,  several
  869.      well-known C string manipulation functions are provided, in-
  870.  
  871.      cluding crypt, index, rindex, length, substr, and sprintf.
  872.  
  873.  
  874.    o The chop function efficiently  removes  the  last  character
  875.      from  a  string.   It's  usually used to delete the trailing
  876.  
  877.      newline on input lines. Like many perl operators,  it  works
  878.      on $_ if no operand is given.
  879.  
  880.  
  881.         chop($line);
  882.  
  883.         chop ($host = `hostname`);
  884.         while (<STDIN>) {
  885.  
  886.             chop; ...
  887.         }
  888.  
  889.  
  890.                      ---------------------------------------
  891.  
  892.                   String functions (continued)
  893.  
  894.  
  895.    o The eval operator lets  you  execute  dynamically  generated
  896.      code.  For example, to process any command line arguments of
  897.  
  898.      the form variable=value, place  this  at  the  top  of  your
  899.      script:
  900.  
  901.  
  902.         eval '$'.$1."'$2';"
  903.  
  904.             while $ARGV[0] =~ /^([A-Za-z_]+=)(.*)/ && shift;
  905.  
  906.  
  907.      The eval operator is also useful  for  run-time  testing  of
  908.      system-dependent  features which would otherwise trigger fa-
  909.  
  910.      tal errors.  For example, not all systems support  the  sym-
  911.      link  or dbmopen; you could test for their existence by exe-
  912.  
  913.      cuting the statements within an eval and testing the special
  914.      variable  $@,  which contains the text of the run-time error
  915.  
  916.      message if anything went wrong.
  917.  
  918.                      ---------------------------------------
  919.  
  920.                           Suid Scripts
  921.  
  922.  
  923.    o Perl programs can be made to run setuid, and can actually be
  924.      more secure than the corresponding C program.
  925.  
  926.  
  927.    o Because interpreters have no  guarantee  that  the  filename
  928.  
  929.      they  get  as  the  first argument is the same file that was
  930.      exec'ed, perl won't let your run a setuid script on a system
  931.  
  932.      where setuid scripts are not disabled.
  933.  
  934.  
  935.    o Using a dataflow tracing mechanism triggered by setuid  exe-
  936.      cution, perl can tell what data is safe to use and what data
  937.  
  938.      comes from an external source and thus is "tainted."
  939.  
  940.  
  941.    o Tainted data may not be used directly or indirectly  in  any
  942.      command  that  modifies  files,  directories or processes or
  943.  
  944.      else a fatal run-time error will result.
  945.  
  946.                      ---------------------------------------
  947.  
  948.                      Debugging and Packages
  949.  
  950.  
  951.    o When invoked with the -d  switch,  perl  runs  your  program
  952.      under a symbolic debugger (written in perl) somewhat similar
  953.  
  954.      to sdb in syntax.  Amongst other things, breakpoints may  be
  955.      set,  variables  examined  or  changed,  and call tracebacks
  956.  
  957.      printed out.  Because it uses eval on your code, you can ex-
  958.      ecute any arbitrary perl code you want from the debugger.
  959.  
  960.  
  961.    o Using  packages  you  can  write   modules   with   separate
  962.  
  963.      namespaces  to  avoid  naming conflicts in library routines.
  964.      The debugger uses this to keep its variables  separate  from
  965.  
  966.      yours.   Variable are accessed by the package'name notation,
  967.      as in this line from the debugger:
  968.  
  969.  
  970.         $DB'stop[$DB'line] =~ s/;9$//;
  971.  
  972.  
  973.                      ---------------------------------------
  974.  
  975.                       Command Line Options
  976.  
  977.  
  978. The following are the more important command line switches recog-
  979. nized by perl:
  980.  
  981.  
  982.    o -v      print out version string
  983.  
  984.    o -w      issue warnings about error-prone constructs
  985.    o -d      run script under the debugger
  986.  
  987.    o -e      like sed: used to enter single command lines
  988.    o -n      loop around input like sed -n
  989.  
  990.    o -p      as with -n but print out each line
  991.    o -i      edit files in place
  992.  
  993.    o -a      turn on autosplit mode (like awk) into @F array
  994.    o -P      call C pre-processor on script
  995.  
  996.  
  997.                      ---------------------------------------
  998.  
  999.                      Examples: Command Line
  1000.  
  1001.  
  1002.    # output current version
  1003.    perl -v
  1004.  
  1005.  
  1006.    # simplest perl program
  1007.  
  1008.    perl -e 'print "hello, world.\n";'
  1009.  
  1010.  
  1011.    # useful at end of "find foo -print"
  1012.    perl -n -e 'chop;unlink;'
  1013.  
  1014.  
  1015.    # add first and last columns (filter)
  1016.  
  1017.    perl -a -n -e 'print $F[0] + $F[$#F], "\n";'
  1018.  
  1019.  
  1020.    # in-place edit of *.c files changing all foo to bar
  1021.    perl -p -i -e 's/\bfoo\b/bar/g;' *.c
  1022.  
  1023.  
  1024.    # run a script under the debugger
  1025.  
  1026.    perl -d myscript
  1027.  
  1028.