home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 January / macformat-020.iso / Shareware City / Applications / Alpha.5.96 folder / Help / Perl Commands < prev    next >
Encoding:
Text File  |  1994-08-20  |  225.4 KB  |  5,322 lines  |  [TEXT/ALFA]

  1. ================================================================================
  2.  
  3.  Note: To install the Perl mode and menu, select the menu item
  4.      "Utils:Install:MacPerl".
  5.  
  6. ================================================================================
  7.  
  8. NAME
  9.      perl - Practical Extraction and Report Language
  10.  
  11. SYNOPSIS
  12.      perl [options] filename args
  13.  
  14. DESCRIPTION
  15.      Perl is an interpreted language optimized for scanning arbi-
  16.      trary  text  files,  extracting  information from those text
  17.      files, and printing reports based on that information.  It's
  18.      also  a good language for many system management tasks.  The
  19.      language is intended to be practical  (easy  to  use,  effi-
  20.      cient,  complete)  rather  than  beautiful  (tiny,  elegant,
  21.      minimal).  It combines (in  the  author's  opinion,  anyway)
  22.      some  of the best features of C, sed, awk, and sh, so people
  23.      familiar with those languages should have little  difficulty
  24.      with  it.  (Language historians will also note some vestiges
  25.      of csh, Pascal,  and  even  BASIC-PLUS.)  Expression  syntax
  26.      corresponds  quite  closely  to C expression syntax.  Unlike
  27.      most Unix utilities, perl does  not  arbitrarily  limit  the
  28.      size  of your data--if you've got the memory, perl can slurp
  29.      in your whole file as a  single  string.   Recursion  is  of
  30.      unlimited  depth.   And  the hash tables used by associative
  31.      arrays grow as necessary to  prevent  degraded  performance.
  32.      Perl  uses sophisticated pattern matching techniques to scan
  33.      large amounts of data very quickly.  Although optimized  for
  34.      scanning  text, perl can also deal with binary data, and can
  35.      make dbm files look like associative arrays  (where  dbm  is
  36.      available).   Setuid  perl scripts are safer than C programs
  37.      through a dataflow tracing  mechanism  which  prevents  many
  38.      stupid  security  holes.   If  you have a problem that would
  39.      ordinarily use sed or awk or sh, but it exceeds their  capa-
  40.      bilities  or must run a little faster, and you don't want to
  41.      write the silly thing in C, then perl may be for you.  There
  42.      are  also  translators to turn your sed and awk scripts into
  43.      perl scripts.  OK, enough hype.
  44.  
  45.      Upon startup, perl looks for your script in one of the  fol-
  46.      lowing places:
  47.  
  48.      1.  Specified line by line via -e switches  on  the  command
  49.          line.
  50.  
  51.      2.  Contained in the file specified by the first filename on
  52.          the  command line.  (Note that systems supporting the #!
  53.          notation invoke interpreters this way.)
  54.  
  55.      3.  Passed in implicitly  via  standard  input.   This  only
  56.          works  if there are no filename arguments--to pass argu-
  57.          ments to a stdin script you must explicitly specify a  -
  58.          for the script name.
  59.  
  60.      After locating your script, perl compiles it to an  internal
  61.      form.   If  the  script is syntactically correct, it is exe-
  62.      cuted.
  63.  
  64.      Options
  65.  
  66.      Note: on first reading this section may not make much  sense
  67.      to you.  It's here at the front for easy reference.
  68.  
  69.      A single-character option may be combined with the following
  70.      option, if any.  This is particularly useful when invoking a
  71.      script using the #! construct which only  allows  one  argu-
  72.      ment.  Example:
  73.  
  74.           #!/usr/bin/perl -spi.bak # same as -s -p -i.bak
  75.           ...
  76.  
  77.      Options include:
  78.  
  79.      -0digits
  80.           specifies the record separator ($/) as an octal number.
  81.           If  there  are  no  digits,  the  null character is the
  82.           separator.  Other switches may precede  or  follow  the
  83.           digits.   For  example,  if  you have a version of find
  84.           which can print filenames terminated by the null  char-
  85.           acter, you can say this:
  86.  
  87.               find . -name '*.bak' -print0 | perl -n0e unlink
  88.  
  89.           The special value 00 will cause Perl to slurp files  in
  90.           paragraph  mode.   The  value  0777  will cause Perl to
  91.           slurp files whole since there  is  no  legal  character
  92.           with that value.
  93.  
  94.      -a   turns on autosplit mode when used with a -n or -p.   An
  95.           implicit  split  command to the @F array is done as the
  96.           first thing inside the implicit while loop produced  by
  97.           the -n or -p.
  98.  
  99.                perl -ane 'print pop(@F), "\n";'
  100.  
  101.           is equivalent to
  102.  
  103.                while (<>) {
  104.                     @F = split(' ');
  105.                     print pop(@F), "\n";
  106.                }
  107.  
  108.      -c   causes perl to check the syntax of the script and  then
  109.           exit without executing it.
  110.  
  111.      -d   runs the script under the perl debugger.  See the  sec-
  112.           tion on Debugging.
  113.  
  114.      -Dnumber
  115.           sets debugging flags.  To watch how  it  executes  your
  116.           script,  use  -D14.   (This  only works if debugging is
  117.           compiled into your perl.) Another nice value is -D1024,
  118.           which  lists  your  compiled  syntax  tree.   And -D512
  119.           displays compiled regular expressions.
  120.  
  121.      -e commandline
  122.           may be used to enter one line of script.   Multiple  -e
  123.           commands  may be given to build up a multi-line script.
  124.           If -e is  given,  perl  will  not  look  for  a  script
  125.           filename in the argument list.
  126.  
  127.      -iextension
  128.           specifies that files processed by the <> construct  are
  129.           to  be  edited  in-place.  It does this by renaming the
  130.           input file, opening the output file by the  same  name,
  131.           and selecting that output file as the default for print
  132.           statements.  The extension, if supplied,  is  added  to
  133.           the  name of the old file to make a backup copy.  If no
  134.           extension is supplied, no backup is made.  Saying "perl
  135.           -p  -i.bak  -e "s/foo/bar/;" ... " is the same as using
  136.           the script:
  137.  
  138.                #!/usr/bin/perl -pi.bak
  139.                s/foo/bar/;
  140.  
  141.           which is equivalent to
  142.  
  143.                #!/usr/bin/perl
  144.                while (<>) {
  145.                     if ($ARGV ne $oldargv) {
  146.                          rename($ARGV, $ARGV . '.bak');
  147.                          open(ARGVOUT, ">$ARGV");
  148.                          select(ARGVOUT);
  149.                          $oldargv = $ARGV;
  150.                     }
  151.                     s/foo/bar/;
  152.                }
  153.                continue {
  154.                    print;     # this prints to original filename
  155.                }
  156.                select(STDOUT);
  157.  
  158.           except that the -i form doesn't need to  compare  $ARGV
  159.           to  $oldargv to know when the filename has changed.  It
  160.           does, however, use ARGVOUT for the selected filehandle.
  161.           Note  that  STDOUT  is  restored  as the default output
  162.           filehandle after the loop.
  163.  
  164.           You can use eof to locate the end of each  input  file,
  165.           in  case you want to append to each file, or reset line
  166.           numbering (see example under eof).
  167.  
  168.      -Idirectory
  169.           may be used in  conjunction  with  -P  to  tell  the  C
  170.           preprocessor  where  to  look  for  include  files.  By
  171.           default /usr/include and /usr/lib/perl are searched.
  172.  
  173.      -loctnum
  174.           enables automatic line-ending processing.  It  has  two
  175.           effects:  first, it automatically chops the line termi-
  176.           nator when used with -n or -p , and second, it  assigns
  177.           $\ to have the value of octnum so that any print state-
  178.           ments will have that line terminator added back on.  If
  179.           octnum  is omitted, sets $\ to the current value of $/.
  180.           For instance, to trim lines to 80 columns:
  181.  
  182.                perl -lpe 'substr($_, 80) = ""'
  183.  
  184.           Note that the assignment $\  =  $/  is  done  when  the
  185.           switch  is processed, so the input record separator can
  186.           be different than the output record separator if the -l
  187.           switch is followed by a -0 switch:
  188.  
  189.                gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
  190.  
  191.           This sets $\ to newline and then sets $/  to  the  null
  192.           character.
  193.  
  194.      -n   causes perl to assume the following  loop  around  your
  195.           script,  which makes it iterate over filename arguments
  196.           somewhat like "sed -n" or awk:
  197.  
  198.                while (<>) {
  199.                     ...       # your script goes here
  200.                }
  201.  
  202.           Note that the lines are not printed by default.  See -p
  203.           to  have  lines  printed.   Here is an efficient way to
  204.           delete all files older than a week:
  205.  
  206.                find . -mtime +7 -print | perl -nle 'unlink;'
  207.  
  208.           This is faster than using  the  -exec  switch  of  find
  209.           because  you  don't  have  to  start a process on every
  210.           filename found.
  211.  
  212.      -p   causes perl to assume the following  loop  around  your
  213.           script,  which makes it iterate over filename arguments
  214.           somewhat like sed:
  215.  
  216.                while (<>) {
  217.                     ...       # your script goes here
  218.                } continue {
  219.                     print;
  220.                }
  221.  
  222.           Note that the  lines  are  printed  automatically.   To
  223.           suppress  printing use the -n switch.  A -p overrides a
  224.           -n switch.
  225.  
  226.      -P   causes your script to be run through the C preprocessor
  227.           before  compilation  by perl.  (Since both comments and
  228.           cpp directives begin with the # character,  you  should
  229.           avoid  starting  comments  with any words recognized by
  230.           the C preprocessor such as "if", "else" or "define".)
  231.  
  232.      -s   enables some rudimentary switch parsing for switches on
  233.           the  command  line after the script name but before any
  234.           filename arguments (or before a --).  Any switch  found
  235.           there  is removed from @ARGV and sets the corresponding
  236.           variable in the  perl  script.   The  following  script
  237.           prints "true" if and only if the script is invoked with
  238.           a -xyz switch.
  239.  
  240.                #!/usr/bin/perl -s
  241.                if ($xyz) { print "true\n"; }
  242.  
  243.      -S   makes perl use the PATH environment variable to  search
  244.           for  the  script  (unless the name of the script starts
  245.           with a slash).  Typically this is used  to  emulate  #!
  246.           startup  on machines that don't support #!, in the fol-
  247.           lowing manner:
  248.  
  249.                #!/usr/bin/perl
  250.                eval "exec /usr/bin/perl -S $0 $*"
  251.                     if $running_under_some_shell;
  252.  
  253.           The system ignores the first line and feeds the  script
  254.           to  /bin/sh,  which proceeds to try to execute the perl
  255.           script as a  shell  script.   The  shell  executes  the
  256.           second  line as a normal shell command, and thus starts
  257.           up the perl interpreter.  On some  systems  $0  doesn't
  258.           always  contain the full pathname, so the -S tells perl
  259.           to search for the  script  if  necessary.   After  perl
  260.           locates  the  script,  it  parses the lines and ignores
  261.           them because the variable $running_under_some_shell  is
  262.           never  true.   A  better  construct  than  $*  would be
  263.           ${1+"$@"}, which handles embedded spaces  and  such  in
  264.           the  filenames, but doesn't work if the script is being
  265.           interpreted by csh.  In order to  start  up  sh  rather
  266.           than  csh, some systems may have to replace the #! line
  267.           with a line containing just a colon, which will be pol-
  268.           itely  ignored  by  perl.   Other systems can't control
  269.           that, and need a totally devious  construct  that  will
  270.           work  under any of csh, sh or perl, such as the follow-
  271.           ing:
  272.  
  273.                eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
  274.                & eval 'exec /usr/bin/perl -S $0 $argv:q'
  275.                     if 0;
  276.  
  277.      -u   causes perl to dump core after compiling  your  script.
  278.           You  can  then  take this core dump and turn it into an
  279.           executable file by using the undump program  (not  sup-
  280.           plied).   This  speeds  startup  at the expense of some
  281.           disk space (which you can  minimize  by  stripping  the
  282.           executable).   (Still, a "hello world" executable comes
  283.           out to about 200K on my machine.) If you are  going  to
  284.           run your executable as a set-id program then you should
  285.           probably compile it using taintperl rather than  normal
  286.           perl.   If you want to execute a portion of your script
  287.           before dumping, use the dump operator  instead.   Note:
  288.           availability of undump is platform specific and may not
  289.           be available for a specific port of perl.
  290.  
  291.      -U   allows perl to do  unsafe  operations.   Currently  the
  292.           only  "unsafe"  operations  are the unlinking of direc-
  293.           tories while running as superuser, and  running  setuid
  294.           programs with fatal taint checks turned into warnings.
  295.  
  296.      -v   prints the version and patchlevel of your perl  execut-
  297.           able.
  298.  
  299.      -w   prints warnings about identifiers  that  are  mentioned
  300.           only  once,  and  scalar variables that are used before
  301.           being set.  Also warns about redefined subroutines, and
  302.           references  to  undefined  filehandles  or  filehandles
  303.           opened readonly that you are attempting  to  write  on.
  304.           Also  warns you if you use == on values that don't look
  305.           like numbers, and if your subroutines recurse more than
  306.           100 deep.
  307.  
  308.      -xdirectory
  309.           tells perl that the script is embedded  in  a  message.
  310.           Leading  garbage will be discarded until the first line
  311.           that starts with #! and  contains  the  string  "perl".
  312.           Any  meaningful  switches  on that line will be applied
  313.           (but only one group of switches, as with normal #! pro-
  314.           cessing).   If a directory name is specified, Perl will
  315.           switch to that directory  before  running  the  script.
  316.           The -x switch only controls the the disposal of leading
  317.           garbage.  The script must be terminated with __END__ if
  318.           there is trailing garbage to be ignored (the script can
  319.           process any or all of the trailing garbage via the DATA
  320.           filehandle if desired).
  321.  
  322.      Data Types and Objects
  323.  
  324.      Perl has three data types: scalars, arrays of  scalars,  and
  325.      associative arrays of scalars.  Normal arrays are indexed by
  326.      number, and associative arrays by string.
  327.  
  328.      The interpretation of operations and values  in  perl  some-
  329.      times  depends on the requirements of the context around the
  330.      operation or value.  There are three major contexts: string,
  331.      numeric  and  array.  Certain operations return array values
  332.      in contexts wanting an array, and scalar  values  otherwise.
  333.      (If this is true of an operation it will be mentioned in the
  334.      documentation for that operation.) Operations  which  return
  335.      scalars  don't  care  whether  the  context is looking for a
  336.      string or a number, but  scalar  variables  and  values  are
  337.      interpreted as strings or numbers as appropriate to the con-
  338.      text.  A scalar is interpreted as TRUE in the boolean  sense
  339.      if  it  is  not  the null string or 0.  Booleans returned by
  340.      operators are 1 for true and 0 or '' (the null  string)  for
  341.      false.
  342.  
  343.      There are actually two varieties of null string: defined and
  344.      undefined.   Undefined  null strings are returned when there
  345.      is no real value for something, such as when  there  was  an
  346.      error, or at end of file, or when you refer to an uninitial-
  347.      ized variable or element of an  array.   An  undefined  null
  348.      string  may become defined the first time you access it, but
  349.      prior to that you can use the defined() operator  to  deter-
  350.      mine whether the value is defined or not.
  351.  
  352.      References to scalar variables always begin with  '$',  even
  353.      when referring to a scalar that is part of an array.  Thus:
  354.  
  355.          $days           # a simple scalar variable
  356.          $days[28]       # 29th element of array @days
  357.          $days{'Feb'}    # one value from an associative array
  358.          $#days          # last index of array @days
  359.  
  360.      but entire arrays or array slices are denoted by '@':
  361.  
  362.          @days           # ($days[0], $days[1],... $days[n])
  363.          @days[3,4,5]    # same as @days[3..5]
  364.          @days{'a','c'}  # same as ($days{'a'},$days{'c'})
  365.  
  366.      and entire associative arrays are denoted by '%':
  367.  
  368.          %days           # (key1, val1, key2, val2 ...)
  369.  
  370.      Any of these eight constructs may serve as an  lvalue,  that
  371.      is,  may be assigned to.  (It also turns out that an assign-
  372.      ment is itself an lvalue in certain  contexts--see  examples
  373.      under  s, tr and chop.) Assignment to a scalar evaluates the
  374.      righthand side in a scalar context, while assignment  to  an
  375.      array  or  array  slice  evaluates  the righthand side in an
  376.      array context.
  377.  
  378.      You may  find  the  length  of  array  @days  by  evaluating
  379.      "$#days",  as in csh.  (Actually, it's not the length of the
  380.      array, it's the subscript of the last element,  since  there
  381.      is  (ordinarily) a 0th element.) Assigning to $#days changes
  382.      the length of the array.  Shortening an array by this method
  383.      does  not actually destroy any values.  Lengthening an array
  384.      that was previously shortened recovers the values that  were
  385.      in  those elements.  You can also gain some measure of effi-
  386.      ciency by preextending an array that is going  to  get  big.
  387.      (You  can  also  extend  an array by assigning to an element
  388.      that is off the end of the array.  This differs from assign-
  389.      ing to $#whatever in that intervening values are set to null
  390.      rather than recovered.) You can truncate an  array  down  to
  391.      nothing  by assigning the null list () to it.  The following
  392.      are exactly equivalent
  393.  
  394.           @whatever = ();
  395.           $#whatever = $[ - 1;
  396.  
  397.      If you evaluate an array in a scalar context, it returns the
  398.      length of the array.  The following is always true:
  399.  
  400.           scalar(@whatever) == $#whatever - $[ + 1;
  401.  
  402.      If you evaluate an associative array in a scalar context, it
  403.      returns  a value which is true if and only if the array con-
  404.      tains any elements.  (If there are any elements,  the  value
  405.      returned  is a string consisting of the number of used buck-
  406.      ets and the number of  allocated  buckets,  separated  by  a
  407.      slash.)
  408.  
  409.      Multi-dimensional arrays are not directly supported, but see
  410.      the  discussion of the $; variable later for a means of emu-
  411.      lating multiple subscripts with an associative  array.   You
  412.      could  also  write  a subroutine to turn multiple subscripts
  413.      into a single subscript.
  414.  
  415.      Every data type has its own  namespace.   You  can,  without
  416.      fear  of  conflict, use the same name for a scalar variable,
  417.      an array, an associative array, a filehandle,  a  subroutine
  418.      name,  and/or  a label.  Since variable and array references
  419.      always start with '$', '@', or  '%',  the  "reserved"  words
  420.      aren't  in  fact  reserved  with  respect to variable names.
  421.  
  422.      (They ARE reserved with respect to labels  and  filehandles,
  423.      however,  which  don't  have  an  initial special character.
  424.      Hint:  you  could  say   open(LOG,'logfile')   rather   than
  425.      open(log,'logfile').    Using   uppercase  filehandles  also
  426.      improves readability and protects  you  from  conflict  with
  427.      future  reserved  words.)  Case IS significant--"FOO", "Foo"
  428.      and "foo" are all different names.  Names which start with a
  429.      letter may also contain digits and underscores.  Names which
  430.      do not start with a letter are  limited  to  one  character,
  431.      e.g.  "$%" or "$$".  (Most of the one character names have a
  432.      predefined significance to perl.  More later.)
  433.  
  434.      Numeric literals are specified in any of the usual  floating
  435.      point or integer formats:
  436.  
  437.          12345
  438.          12345.67
  439.          .23E-10
  440.          0xffff     # hex
  441.          0377  # octal
  442.  
  443.      String literals are delimited by  either  single  or  double
  444.      quotes.   They  work  much  like shell quotes: double-quoted
  445.      string literals are subject to backslash and  variable  sub-
  446.      stitution;  single-quoted strings are not (except for \' and
  447.      \\).  The usual backslash rules apply for making  characters
  448.      such  as  newline,  tab,  etc.,  as well as some more exotic
  449.      forms:
  450.  
  451.           \t        tab
  452.           \n        newline
  453.           \r        return
  454.           \f        form feed
  455.           \b        backspace
  456.           \a        alarm (bell)
  457.           \e        escape
  458.           \033      octal char
  459.           \x1b      hex char
  460.           \c[       control char
  461.           \l        lowercase next char
  462.           \u        uppercase next char
  463.           \L        lowercase till \E
  464.           \U        uppercase till \E
  465.           \E        end case modification
  466.  
  467.      You can also embed newlines directly in your  strings,  i.e.
  468.      they  can  end on a different line than they begin.  This is
  469.      nice, but if you forget your trailing quote, the error  will
  470.      not be reported until perl finds another line containing the
  471.      quote character, which may be much further on in the script.
  472.      Variable  substitution  inside  strings is limited to scalar
  473.      variables, normal array values, and array slices.  (In other
  474.      words,  identifiers  beginning  with  $ or @, followed by an
  475.      optional bracketed expression as a subscript.) The following
  476.      code segment prints out "The price is $100."
  477.  
  478.          $Price = '$100';               # not interpreted
  479.          print "The price is $Price.\n";# interpreted
  480.  
  481.      Note that you can put curly brackets around  the  identifier
  482.      to  delimit it from following alphanumerics.  Also note that
  483.      a single quoted string must be separated  from  a  preceding
  484.      word  by a space, since single quote is a valid character in
  485.      an identifier (see Packages).
  486.  
  487.      Two  special  literals  are  __LINE__  and  __FILE__,  which
  488.      represent the current line number and filename at that point
  489.      in your program.  They may only be used as separate  tokens;
  490.      they  will  not  be interpolated into strings.  In addition,
  491.      the token __END__ may be used to indicate the logical end of
  492.      the  script  before  the  actual end of file.  Any following
  493.      text is ignored (but may be read via the  DATA  filehandle).
  494.      The  two  control  characters  ^D  and  ^Z  are synonyms for
  495.      __END__.
  496.  
  497.      A word that doesn't have any  other  interpretation  in  the
  498.      grammar  will  be  treated as if it had single quotes around
  499.      it.  For this purpose, a word consists only of  alphanumeric
  500.      characters  and underline, and must start with an alphabetic
  501.      character.  As with filehandles and labels, a bare word that
  502.      consists  entirely  of lowercase letters risks conflict with
  503.      future reserved words, and if you use the  -w  switch,  Perl
  504.      will warn you about any such words.
  505.  
  506.      Array values are interpolated into double-quoted strings  by
  507.      joining  all  the  elements  of the array with the delimiter
  508.      specified in the $" variable, space by default.   (Since  in
  509.      versions  of  perl  prior  to  3.0 the @ character was not a
  510.      metacharacter in double-quoted strings, the interpolation of
  511.      @array,   $array[EXPR],   @array[LIST],   $array{EXPR},   or
  512.      @array{LIST} only happens if array is  referenced  elsewhere
  513.      in   the  program  or  is  predefined.)  The  following  are
  514.      equivalent:
  515.  
  516.           $temp = join($",@ARGV);
  517.           system "echo $temp";
  518.  
  519.           system "echo @ARGV";
  520.  
  521.      Within search patterns (which  also  undergo  double-quotish
  522.      substitution)  there  is a bad ambiguity:  Is /$foo[bar]/ to
  523.      be interpreted as /${foo}[bar]/ (where [bar] is a  character
  524.      class for the regular expression) or as /${foo[bar]}/ (where
  525.      [bar] is the subscript to  array  @foo)?   If  @foo  doesn't
  526.      otherwise  exist, then it's obviously a character class.  If
  527.      @foo exists, perl takes a good guess  about  [bar],  and  is
  528.      almost  always  right.  If it does guess wrong, or if you're
  529.      just plain paranoid, you can force the  correct  interpreta-
  530.      tion with curly brackets as above.
  531.  
  532.      A line-oriented form of quoting is based on the shell  here-
  533.      is syntax.  Following a << you specify a string to terminate
  534.      the quoted material, and all  lines  following  the  current
  535.      line  down  to  the  terminating string are the value of the
  536.      item.  The terminating string may be either an identifier (a
  537.      word),  or  some quoted text.  If quoted, the type of quotes
  538.      you use determines the treatment of the  text,  just  as  in
  539.      regular  quoting.   An unquoted identifier works like double
  540.      quotes.  There must be no space between the << and the iden-
  541.      tifier.   (If  you  put a space it will be treated as a null
  542.      identifier, which is valid,  and  matches  the  first  blank
  543.      line--see  Merry  Christmas  example below.) The terminating
  544.      string must appear by itself (unquoted and with no surround-
  545.      ing whitespace) on the terminating line.
  546.  
  547.           print <<EOF;        # same as above
  548.      The price is $Price.
  549.      EOF
  550.  
  551.           print <<"EOF";      # same as above
  552.      The price is $Price.
  553.      EOF
  554.  
  555.           print << x 10;      # null identifier is delimiter
  556.      Merry Christmas!
  557.  
  558.           print <<`EOC`;      # execute commands
  559.      echo hi there
  560.      echo lo there
  561.      EOC
  562.  
  563.           print <<foo, <<bar; # you can stack them
  564.      I said foo.
  565.      foo
  566.      I said bar.
  567.      bar
  568.  
  569.      Array literals are denoted by separating  individual  values
  570.      by commas, and enclosing the list in parentheses:
  571.  
  572.           (LIST)
  573.  
  574.      In a context not requiring an array value, the value of  the
  575.      array literal is the value of the final element, as in the C
  576.      comma operator.  For example,
  577.  
  578.          @foo = ('cc', '-E', $bar);
  579.  
  580.      assigns the entire array value to array foo, but
  581.  
  582.          $foo = ('cc', '-E', $bar);
  583.  
  584.      assigns the value of variable bar  to  variable  foo.   Note
  585.      that the value of an actual array in a scalar context is the
  586.      length of the array; the following assigns to $foo the value
  587.      3:
  588.  
  589.          @foo = ('cc', '-E', $bar);
  590.          $foo = @foo;         # $foo gets 3
  591.  
  592.      You  may  have  an  optional  comma   before   the   closing
  593.      parenthesis of an array literal, so that you can say:
  594.  
  595.          @foo = (
  596.           1,
  597.           2,
  598.           3,
  599.          );
  600.  
  601.      When a LIST is  evaluated,  each  element  of  the  list  is
  602.      evaluated in an array context, and the resulting array value
  603.      is interpolated into LIST just as if each individual element
  604.      were a member of LIST.  Thus arrays lose their identity in a
  605.      LIST--the list
  606.  
  607.           (@foo,@bar,&SomeSub)
  608.  
  609.      contains all the elements of @foo followed by all  the  ele-
  610.      ments  of @bar, followed by all the elements returned by the
  611.      subroutine named SomeSub.
  612.  
  613.      A list value may also be subscripted like  a  normal  array.
  614.      Examples:
  615.  
  616.           $time = (stat($file))[8];     # stat returns array value
  617.           $digit = ('a','b','c','d','e','f')[$digit-10];
  618.           return (pop(@foo),pop(@foo))[0];
  619.  
  620.      Array lists may be assigned to if and only if  each  element
  621.      of the list is an lvalue:
  622.  
  623.          ($a, $b, $c) = (1, 2, 3);
  624.  
  625.          ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  626.  
  627.      The final element may be an array or an associative array:
  628.  
  629.          ($a, $b, @rest) = split;
  630.          local($a, $b, %rest) = @_;
  631.  
  632.      You can actually put an array anywhere in the list, but  the
  633.      first  array  in  the  list will soak up all the values, and
  634.      anything after it will get a null value.  This may be useful
  635.      in a local().
  636.  
  637.      An associative array literal contains pairs of values to  be
  638.      interpreted as a key and a value:
  639.  
  640.          # same as map assignment above
  641.          %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  642.  
  643.      Array assignment in a scalar context returns the  number  of
  644.      elements produced by the expression on the right side of the
  645.      assignment:
  646.  
  647.           $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
  648.  
  649.      There are several other pseudo-literals that you should know
  650.      about.    If  a  string  is  enclosed  by  backticks  (grave
  651.      accents), it first undergoes variable substitution just like
  652.      a  double  quoted  string.  It is then interpreted as a com-
  653.      mand, and the output of that command is  the  value  of  the
  654.      pseudo-literal,  like  in  a  shell.  In a scalar context, a
  655.      single string consisting of all the output is returned.   In
  656.      an  array  context,  an array of values is returned, one for
  657.      each line of output.  (You can set $/  to  use  a  different
  658.      line  terminator.)  The  command  is  executed each time the
  659.      pseudo-literal is evaluated.  The status value of  the  com-
  660.      mand  is  returned  in  $?  (see  Predefined  Names  for the
  661.      interpretation of $?).  Unlike in  csh,  no  translation  is
  662.      done  on  the return data--newlines remain newlines.  Unlike
  663.      in any of the shells, single quotes  do  not  hide  variable
  664.      names  in  the  command  from  interpretation.   To pass a $
  665.      through to the shell you need to hide it with a backslash.
  666.  
  667.      Evaluating a filehandle in angle brackets  yields  the  next
  668.      line  from  that file (newline included, so it's never false
  669.      until EOF, at which time an undefined  value  is  returned).
  670.      Ordinarily  you  must  assign  that value to a variable, but
  671.      there is one situation where an  automatic  assignment  hap-
  672.      pens.   If  (and only if) the input symbol is the only thing
  673.      inside the  conditional  of  a  while  loop,  the  value  is
  674.      automatically assigned to the variable "$_".  (This may seem
  675.      like an odd thing to you, but you'll use  the  construct  in
  676.      almost  every  perl script you write.) Anyway, the following
  677.      lines are equivalent to each other:
  678.  
  679.          while ($_ = <STDIN>) { print; }
  680.          while (<STDIN>) { print; }
  681.          for (;<STDIN>;) { print; }
  682.          print while $_ = <STDIN>;
  683.          print while <STDIN>;
  684.  
  685.      The filehandles STDIN, STDOUT  and  STDERR  are  predefined.
  686.      (The  filehandles  stdin,  stdout  and stderr will also work
  687.      except in packages, where they would be interpreted as local
  688.      identifiers  rather than global.) Additional filehandles may
  689.      be created with the open function.
  690.  
  691.      If a <FILEHANDLE> is used in a context that is  looking  for
  692.      an  array,  an  array  consisting  of all the input lines is
  693.      returned, one line per array element.  It's easy to  make  a
  694.      LARGE data space this way, so use with care.
  695.  
  696.      The null filehandle <> is special and can be used to emulate
  697.      the  behavior  of  sed  and awk.  Input from <> comes either
  698.      from standard input, or from each file listed on the command
  699.      line.   Here's how it works: the first time <> is evaluated,
  700.      the ARGV array is checked, and if it is  null,  $ARGV[0]  is
  701.      set to '-', which when opened gives you standard input.  The
  702.      ARGV array is then processed as a list  of  filenames.   The
  703.      loop
  704.  
  705.           while (<>) {
  706.                ...            # code for each line
  707.           }
  708.  
  709.      is equivalent to
  710.  
  711.           unshift(@ARGV, '-') if $#ARGV < $[;
  712.           while ($ARGV = shift) {
  713.                open(ARGV, $ARGV);
  714.                while (<ARGV>) {
  715.                     ...       # code for each line
  716.                }
  717.           }
  718.  
  719.      except that it isn't as cumbersome to say.  It  really  does
  720.      shift  array ARGV and put the current filename into variable
  721.      ARGV.  It also uses filehandle  ARGV  internally.   You  can
  722.      modify  @ARGV  before  the first <> as long as you leave the
  723.      first filename at the beginning of the array.  Line  numbers
  724.      ($.)  continue as if the input was one big happy file.  (But
  725.      see example under eof for how to reset line numbers on  each
  726.      file.)
  727.  
  728.      If you want to set @ARGV to your own list of files, go right
  729.      ahead.   If  you want to pass switches into your script, you
  730.      can put a loop on the front like this:
  731.  
  732.           while ($_ = $ARGV[0], /^-/) {
  733.                shift;
  734.               last if /^--$/;
  735.                /^-D(.*)/ && ($debug = $1);
  736.                /^-v/ && $verbose++;
  737.                ...       # other switches
  738.           }
  739.           while (<>) {
  740.                ...       # code for each line
  741.           }
  742.  
  743.      The <> symbol will return FALSE only once.  If you  call  it
  744.      again  after  this it will assume you are processing another
  745.      @ARGV list, and if you haven't set @ARGV,  will  input  from
  746.      STDIN.
  747.  
  748.      If the string inside the angle brackets is a reference to  a
  749.      scalar  variable  (e.g. <$foo>), then that variable contains
  750.      the name of the filehandle to input from.
  751.  
  752.      If the string inside angle brackets is not a filehandle,  it
  753.      is  interpreted  as  a  filename  pattern to be globbed, and
  754.      either an array of filenames or the  next  filename  in  the
  755.      list  is  returned,  depending  on  context.  One level of $
  756.      interpretation is done  first,  but  you  can't  say  <$foo>
  757.      because  that's  an  indirect filehandle as explained in the
  758.      previous paragraph.  You  could  insert  curly  brackets  to
  759.      force interpretation as a filename glob: <${foo}>.  Example:
  760.  
  761.           while (<*.c>) {
  762.                chmod 0644, $_;
  763.           }
  764.  
  765.      is equivalent to
  766.  
  767.           open(foo, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  768.           while (<foo>) {
  769.                chop;
  770.                chmod 0644, $_;
  771.           }
  772.  
  773.      In fact, it's currently implemented that way.  (Which  means
  774.      it will not work on filenames with spaces in them unless you
  775.      have /bin/csh on your machine.) Of course, the shortest  way
  776.      to do the above is:
  777.  
  778.           chmod 0644, <*.c>;
  779.  
  780.      Syntax
  781.  
  782.      A perl script consists of a  sequence  of  declarations  and
  783.      commands.   The only things that need to be declared in perl
  784.      are report formats and subroutines.  See the sections  below
  785.      for  more information on those declarations.  All uninitial-
  786.      ized user-created objects are assumed to start with  a  null
  787.      or 0 value until they are defined by some explicit operation
  788.      such as assignment.  The sequence of  commands  is  executed
  789.      just once, unlike in sed and awk scripts, where the sequence
  790.      of commands is executed for each  input  line.   While  this
  791.      means  that  you must explicitly loop over the lines of your
  792.      input file (or files), it also means you have much more con-
  793.      trol  over  which files and which lines you look at.  (Actu-
  794.      ally, I'm lying--it is possible to do an implicit loop  with
  795.      either the -n or -p switch.)
  796.  
  797.      A declaration can be put anywhere a command can, but has  no
  798.      effect   on   the  execution  of  the  primary  sequence  of
  799.      commands--declarations all  take  effect  at  compile  time.
  800.      Typically  all  the declarations are put at the beginning or
  801.      the end of the script.
  802.  
  803.      Perl is, for the most part, a free-form language.  (The only
  804.      exception to this is format declarations, for fairly obvious
  805.      reasons.) Comments are indicated by  the  #  character,  and
  806.      extend  to the end of the line.  If you attempt to use /* */
  807.      C comments, it will be interpreted  either  as  division  or
  808.      pattern  matching,  depending  on  the context.  So don't do
  809.      that.
  810.  
  811.      Compound statements
  812.  
  813.      In perl, a sequence of commands may be treated as  one  com-
  814.      mand by enclosing it in curly brackets.  We will call this a
  815.      BLOCK.
  816.  
  817.      The following compound commands may be used to control flow:
  818.  
  819.           if (EXPR) BLOCK
  820.           if (EXPR) BLOCK else BLOCK
  821.           if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  822.           LABEL while (EXPR) BLOCK
  823.           LABEL while (EXPR) BLOCK continue BLOCK
  824.           LABEL for (EXPR; EXPR; EXPR) BLOCK
  825.           LABEL foreach VAR (ARRAY) BLOCK
  826.           LABEL BLOCK continue BLOCK
  827.  
  828.      Note that, unlike C and Pascal, these are defined  in  terms
  829.      of BLOCKs, not statements.  This means that the curly brack-
  830.      ets are required--no dangling statements  allowed.   If  you
  831.      want  to write conditionals without curly brackets there are
  832.      several other ways to do it.  The following all do the  same
  833.      thing:
  834.  
  835.           if (!open(foo)) { die "Can't open $foo: $!"; }
  836.           die "Can't open $foo: $!" unless open(foo);
  837.           open(foo) || die "Can't open $foo: $!"; # foo or bust!
  838.           open(foo) ? 'hi mom' : die "Can't open $foo: $!";
  839.                          # a bit exotic, that last one
  840.  
  841.      The if  statement  is  straightforward.   Since  BLOCKs  are
  842.      always  bounded  by curly brackets, there is never any ambi-
  843.      guity about which if an else goes with.  If you  use  unless
  844.      in place of if, the sense of the test is reversed.
  845.  
  846.      The while statement  executes  the  block  as  long  as  the
  847.      expression  is true (does not evaluate to the null string or
  848.      0).  The LABEL is optional, and if present, consists  of  an
  849.      identifier  followed  by  a colon.  The LABEL identifies the
  850.      loop for the loop control statements next,  last,  and  redo
  851.      (see  below).   If  there  is a continue BLOCK, it is always
  852.      executed  just  before  the  conditional  is  about  to   be
  853.      evaluated  again,  similarly to the third part of a for loop
  854.      in C.  Thus it can be used to  increment  a  loop  variable,
  855.      even when the loop has been continued via the next statement
  856.      (similar to the C "continue" statement).
  857.  
  858.      If the word while is replaced by the word until,  the  sense
  859.      of the test is reversed, but the conditional is still tested
  860.      before the first iteration.
  861.  
  862.      In either the if or the while  statement,  you  may  replace
  863.      "(EXPR)"  with  a  BLOCK, and the conditional is true if the
  864.      value of the last command in that block is true.
  865.  
  866.      The for loop works  exactly  like  the  corresponding  while
  867.      loop:
  868.  
  869.           for ($i = 1; $i < 10; $i++) {
  870.                ...
  871.           }
  872.  
  873.      is the same as
  874.  
  875.           $i = 1;
  876.           while ($i < 10) {
  877.                ...
  878.           } continue {
  879.                $i++;
  880.           }
  881.  
  882.      The foreach loop iterates over a normal array value and sets
  883.      the  variable  VAR  to be each element of the array in turn.
  884.      The variable is implicitly local to the  loop,  and  regains
  885.      its  former value upon exiting the loop.  The "foreach" key-
  886.      word is actually identical to the "for" keyword, so you  can
  887.      use  "foreach" for readability or "for" for brevity.  If VAR
  888.      is omitted, $_ is set to each value.  If ARRAY is an  actual
  889.      array  (as  opposed  to  an  expression  returning  an array
  890.      value), you can modify each element of the array by  modify-
  891.      ing VAR inside the loop.  Examples:
  892.  
  893.           for (@ary) { s/foo/bar/; }
  894.  
  895.           foreach $elem (@elements) {
  896.                $elem *= 2;
  897.           }
  898.  
  899.           for ((10,9,8,7,6,5,4,3,2,1,'BOOM')) {
  900.                print $_, "\n"; sleep(1);
  901.           }
  902.  
  903.           for (1..15) { print "Merry Christmas\n"; }
  904.  
  905.           foreach $item (split(/:[\\\n:]*/, $ENV{'TERMCAP'})) {
  906.                print "Item: $item\n";
  907.           }
  908.  
  909.      The BLOCK by itself (labeled or not) is equivalent to a loop
  910.      that  executes  once.  Thus you can use any of the loop con-
  911.      trol statements in it to leave or restart  the  block.   The
  912.      continue  block is optional.  This construct is particularly
  913.      nice for doing case structures.
  914.  
  915.           foo: {
  916.                if (/^abc/) { $abc = 1; last foo; }
  917.                if (/^def/) { $def = 1; last foo; }
  918.                if (/^xyz/) { $xyz = 1; last foo; }
  919.                $nothing = 1;
  920.           }
  921.  
  922.      There is no official switch statement in perl, because there
  923.      are  already several ways to write the equivalent.  In addi-
  924.      tion to the above, you could write
  925.  
  926.           foo: {
  927.                $abc = 1, last foo  if /^abc/;
  928.                $def = 1, last foo  if /^def/;
  929.                $xyz = 1, last foo  if /^xyz/;
  930.                $nothing = 1;
  931.           }
  932.  
  933.      or
  934.  
  935.           foo: {
  936.                /^abc/ && do { $abc = 1; last foo; };
  937.                /^def/ && do { $def = 1; last foo; };
  938.                /^xyz/ && do { $xyz = 1; last foo; };
  939.                $nothing = 1;
  940.           }
  941.  
  942.      or
  943.  
  944.           foo: {
  945.                /^abc/ && ($abc = 1, last foo);
  946.                /^def/ && ($def = 1, last foo);
  947.                /^xyz/ && ($xyz = 1, last foo);
  948.                $nothing = 1;
  949.           }
  950.  
  951.      or even
  952.  
  953.           if (/^abc/)
  954.                { $abc = 1; }
  955.           elsif (/^def/)
  956.                { $def = 1; }
  957.           elsif (/^xyz/)
  958.                { $xyz = 1; }
  959.           else
  960.                {$nothing = 1;}
  961.  
  962.      As it happens, these  are  all  optimized  internally  to  a
  963.      switch  structure,  so  perl  jumps  directly to the desired
  964.      statement, and you needn't worry about perl executing a  lot
  965.      of  unnecessary  statements  when  you  have  a string of 50
  966.      elsifs, as long as you are testing the  same  simple  scalar
  967.      variable  using  ==,  eq, or pattern matching as above.  (If
  968.      you're curious as to whether the optimizer has done this for
  969.      a  particular  case statement, you can use the -D1024 switch
  970.      to list the syntax tree before execution.)
  971.  
  972.      Simple statements
  973.  
  974.      The only kind of simple statement is an expression evaluated
  975.      for  its  side effects.  Every expression (simple statement)
  976.      must be terminated with a semicolon.  Note that this is like
  977.      C, but unlike Pascal (and awk).
  978.  
  979.      Any simple statement may optionally be followed by a  single
  980.      modifier, just before the terminating semicolon.  The possi-
  981.      ble modifiers are:
  982.  
  983.           if EXPR
  984.           unless EXPR
  985.           while EXPR
  986.           until EXPR
  987.  
  988.      The if and unless modifiers  have  the  expected  semantics.
  989.      The  while and until modifiers also have the expected seman-
  990.      tics (conditional evaluated first), except when applied to a
  991.      do-BLOCK or a do-SUBROUTINE command, in which case the block
  992.      executes once before the conditional is evaluated.  This  is
  993.      so that you can write loops like:
  994.  
  995.           do {
  996.                $_ = <STDIN>;
  997.                ...
  998.           } until $_ eq ".\n";
  999.  
  1000.      (See the do operator below.  Note also that the loop control
  1001.      commands  described  later  will NOT work in this construct,
  1002.      since modifiers don't take loop labels.  Sorry.)
  1003.  
  1004.      Expressions
  1005.  
  1006.      Since perl expressions work almost exactly  like  C  expres-
  1007.      sions, only the differences will be mentioned here.
  1008.  
  1009.      Here's what perl has that C doesn't:
  1010.  
  1011.      **      The exponentiation operator.
  1012.  
  1013.      **=     The exponentiation assignment operator.
  1014.  
  1015.      ()      The null list, used to initialize an array to null.
  1016.  
  1017.      .       Concatenation of two strings.
  1018.  
  1019.      .=      The concatenation assignment operator.
  1020.  
  1021.      eq      String equality (== is  numeric  equality).   For  a
  1022.              mnemonic  just  think  of "eq" as a string.  (If you
  1023.              are used to the awk behavior of using == for  either
  1024.              string or numeric equality based on the current form
  1025.              of the comparands, beware!   You  must  be  explicit
  1026.              here.)
  1027.  
  1028.      ne      String inequality (!= is numeric inequality).
  1029.  
  1030.      lt      String less than.
  1031.  
  1032.      gt      String greater than.
  1033.  
  1034.      le      String less than or equal.
  1035.  
  1036.      ge      String greater than or equal.
  1037.  
  1038.      cmp     String comparison, returning -1, 0, or 1.
  1039.  
  1040.      <=>     Numeric comparison, returning -1, 0, or 1.
  1041.  
  1042.      =~      Certain operations search or modify the string  "$_"
  1043.              by default.  This operator makes that kind of opera-
  1044.              tion work on some other string.  The right  argument
  1045.              is  a  search pattern, substitution, or translation.
  1046.              The  left  argument  is  what  is  supposed  to   be
  1047.              searched,  substituted, or translated instead of the
  1048.              default "$_".  The return value indicates  the  suc-
  1049.              cess of the operation.  (If the right argument is an
  1050.              expression other than a  search  pattern,  substitu-
  1051.              tion,  or translation, it is interpreted as a search
  1052.              pattern at run time.  This is less efficient than an
  1053.              explicit  search, since the pattern must be compiled
  1054.              every time the expression is  evaluated.)  The  pre-
  1055.              cedence  of  this operator is lower than unary minus
  1056.              and autoincrement/decrement, but higher than  every-
  1057.              thing else.
  1058.  
  1059.      !~      Just like =~ except the return value is negated.
  1060.  
  1061.      x       The repetition operator.  Returns a string  consist-
  1062.              ing of the left operand repeated the number of times
  1063.              specified by the right operand.  In  an  array  con-
  1064.              text,  if  the  left operand is a list in parens, it
  1065.              repeats the list.
  1066.  
  1067.                   print '-' x 80;          # print row of dashes
  1068.                   print '-' x80;      # illegal, x80 is identifier
  1069.  
  1070.                   print "\t" x ($tab/8), ' ' x ($tab%8);  # tab over
  1071.  
  1072.                   @ones = (1) x 80;        # an array of 80 1's
  1073.                   @ones = (5) x @ones;          # set all elements to 5
  1074.  
  1075.      x=      The repetition assignment operator.  Only  works  on
  1076.              scalars.
  1077.  
  1078.      ..      The range operator, which is  really  two  different
  1079.              operators  depending  on  the  context.  In an array
  1080.              context, returns an array  of  values  counting  (by
  1081.              ones)  from the left value to the right value.  This
  1082.              is useful for writing "for (1..10)"  loops  and  for
  1083.              doing slice operations on arrays.
  1084.  
  1085.              In a scalar context, ..  returns  a  boolean  value.
  1086.              The  operator  is bistable, like a flip-flop..  Each
  1087.              .. operator maintains its own boolean state.  It  is
  1088.              false  as  long  as its left operand is false.  Once
  1089.              the left operand is true, the range  operator  stays
  1090.              true  until  the  right operand is true, AFTER which
  1091.              the range operator becomes false again.  (It doesn't
  1092.              become  false  till the next time the range operator
  1093.              is evaluated.  It  can  become  false  on  the  same
  1094.              evaluation it became true, but it still returns true
  1095.              once.) The right operand is not evaluated while  the
  1096.              operator  is  in  the  "false"  state,  and the left
  1097.              operand is not evaluated while the  operator  is  in
  1098.              the  "true"  state.   The scalar .. operator is pri-
  1099.              marily intended for doing line number  ranges  after
  1100.              the fashion of sed or awk.  The precedence is a lit-
  1101.              tle lower than || and &&.   The  value  returned  is
  1102.              either  the  null  string  for  false, or a sequence
  1103.              number (beginning with 1) for  true.   The  sequence
  1104.              number  is  reset  for  each range encountered.  The
  1105.              final sequence number in a range has the string 'E0'
  1106.              appended  to  it,  which  doesn't affect its numeric
  1107.              value, but gives you something to search for if  you
  1108.              want  to  exclude the endpoint.  You can exclude the
  1109.              beginning point by waiting for the  sequence  number
  1110.              to  be  greater than 1.  If either operand of scalar
  1111.              .. is static, that operand is implicitly compared to
  1112.              the $. variable, the current line number.  Examples:
  1113.  
  1114.              As a scalar operator:
  1115.                  if (101 .. 200) { print; }     # print 2nd hundred lines
  1116.  
  1117.                  next line if (1 .. /^$/); # skip header lines
  1118.  
  1119.                  s/^/> / if (/^$/ .. eof());    # quote body
  1120.  
  1121.              As an array operator:
  1122.                  for (101 .. 200) { print; }    # print $_ 100 times
  1123.  
  1124.                  @foo = @foo[$[ .. $#foo]; # an expensive no-op
  1125.                  @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
  1126.  
  1127.      -x      A file test.  This unary operator  takes  one  argu-
  1128.              ment,  either  a filename or a filehandle, and tests
  1129.              the associated file to  see  if  something  is  true
  1130.              about  it.   If  the  argument is omitted, tests $_,
  1131.              except for -t, which tests STDIN.  It returns 1  for
  1132.              true and '' for false, or the undefined value if the
  1133.              file doesn't exist.  Precedence is higher than logi-
  1134.              cal  and relational operators, but lower than arith-
  1135.              metic operators.  The operator may be any of:
  1136.  
  1137.                   -r   File is readable by effective uid.
  1138.                   -w   File is writable by effective uid.
  1139.                   -x   File is executable by effective uid.
  1140.                   -o   File is owned by effective uid.
  1141.                   -R   File is readable by real uid.
  1142.                   -W   File is writable by real uid.
  1143.                   -X   File is executable by real uid.
  1144.                   -O   File is owned by real uid.
  1145.                   -e   File exists.
  1146.                   -z   File has zero size.
  1147.                   -s   File has non-zero size (returns size).
  1148.                   -f   File is a plain file.
  1149.                   -d   File is a directory.
  1150.                   -l   File is a symbolic link.
  1151.                   -p   File is a named pipe (FIFO).
  1152.                   -S   File is a socket.
  1153.                   -b   File is a block special file.
  1154.                   -c   File is a character special file.
  1155.                   -u   File has setuid bit set.
  1156.                   -g   File has setgid bit set.
  1157.                   -k   File has sticky bit set.
  1158.                   -t   Filehandle is opened to a tty.
  1159.                   -T   File is a text file.
  1160.                   -B   File is a binary file (opposite of -T).
  1161.                   -M   Age of file in days when script started.
  1162.                   -A   Same for access time.
  1163.                   -C   Same for inode change time.
  1164.  
  1165.              The interpretation of the file permission  operators
  1166.              -r,  -R,  -w,  -W,  -x and -X is based solely on the
  1167.              mode of the file and the uids and gids of the  user.
  1168.              There  may be other reasons you can't actually read,
  1169.              write or execute the file.  Also note that, for  the
  1170.              superuser, -r, -R, -w and -W always return 1, and -x
  1171.              and -X return 1 if any execute bit  is  set  in  the
  1172.              mode.  Scripts run by the superuser may thus need to
  1173.              do a stat() in order to determine the actual mode of
  1174.              the  file,  or  temporarily set the uid to something
  1175.              else.
  1176.  
  1177.              Example:
  1178.  
  1179.                   while (<>) {
  1180.                        chop;
  1181.                        next unless -f $_;  # ignore specials
  1182.                        ...
  1183.                   }
  1184.  
  1185.              Note that -s/a/b/ does not do  a  negated  substitu-
  1186.              tion.   Saying  -exp($foo)  still works as expected,
  1187.              however--only single letters following a  minus  are
  1188.              interpreted as file tests.
  1189.  
  1190.              The -T and -B switches work as follows.   The  first
  1191.              block  or so of the file is examined for odd charac-
  1192.              ters such as strange control  codes  or  metacharac-
  1193.              ters.   If too many odd characters (>10%) are found,
  1194.              it's a -B file, otherwise it's a -T file.  Also, any
  1195.              file  containing  null  in  the  first block is con-
  1196.              sidered a binary file.  If -T or -B  is  used  on  a
  1197.              filehandle,  the  current  stdio  buffer is examined
  1198.              rather than the first block.  Both -T and -B  return
  1199.              TRUE on a null file, or a file at EOF when testing a
  1200.              filehandle.
  1201.  
  1202.      If any of the file tests (or either stat operator) are given
  1203.      the  special  filehandle consisting of a solitary underline,
  1204.      then the stat structure of the previous file test  (or  stat
  1205.      operator) is used, saving a system call.  (This doesn't work
  1206.      with -t, and you need to remember that  lstat  and  -l  will
  1207.      leave  values  in  the stat structure for the symbolic link,
  1208.      not the real file.) Example:
  1209.  
  1210.           print "Can do.\n" if -r $a || -w _ || -x _;
  1211.  
  1212.           stat($filename);
  1213.           print "Readable\n" if -r _;
  1214.           print "Writable\n" if -w _;
  1215.           print "Executable\n" if -x _;
  1216.           print "Setuid\n" if -u _;
  1217.           print "Setgid\n" if -g _;
  1218.           print "Sticky\n" if -k _;
  1219.           print "Text\n" if -T _;
  1220.           print "Binary\n" if -B _;
  1221.  
  1222.      Here is what C has that perl doesn't:
  1223.  
  1224.      unary &     Address-of operator.
  1225.  
  1226.      unary *     Dereference-address operator.
  1227.  
  1228.      (TYPE)      Type casting operator.
  1229.  
  1230.      Like C, perl does a certain amount of expression  evaluation
  1231.      at  compile  time,  whenever  it  determines that all of the
  1232.      arguments to  an  operator  are  static  and  have  no  side
  1233.      effects.   In  particular,  string  concatenation happens at
  1234.      compile time between literals that don't do variable substi-
  1235.      tution.   Backslash  interpretation  also happens at compile
  1236.      time.  You can say
  1237.  
  1238.           'Now is the time for all' . "\n" .
  1239.           'good men to come to.'
  1240.  
  1241.      and this all reduces to one string internally.
  1242.  
  1243.      The autoincrement operator has a little extra built-in magic
  1244.      to it.  If you increment a variable that is numeric, or that
  1245.      has ever been used in a numeric context, you  get  a  normal
  1246.      increment.   If, however, the variable has only been used in
  1247.      string contexts since it was set, and has a  value  that  is
  1248.      not  null  and  matches the pattern /^[a-zA-Z]*[0-9]*$/, the
  1249.      increment is done as a  string,  preserving  each  character
  1250.      within its range, with carry:
  1251.  
  1252.           print ++($foo = '99');   # prints '100'
  1253.           print ++($foo = 'a0');   # prints 'a1'
  1254.           print ++($foo = 'Az');   # prints 'Ba'
  1255.           print ++($foo = 'zz');   # prints 'aaa'
  1256.  
  1257.      The autodecrement is not magical.
  1258.  
  1259.      The range operator (in an array context) makes  use  of  the
  1260.      magical  autoincrement  algorithm if the minimum and maximum
  1261.      are strings.  You can say
  1262.  
  1263.           @alphabet = ('A' .. 'Z');
  1264.  
  1265.      to get all the letters of the alphabet, or
  1266.  
  1267.           $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  1268.  
  1269.      to get a hexadecimal digit, or
  1270.  
  1271.           @z2 = ('01' .. '31');  print @z2[$mday];
  1272.  
  1273.      to get dates with leading zeros.  (If the final value speci-
  1274.      fied is not in the sequence that the magical increment would
  1275.      produce, the sequence goes until the  next  value  would  be
  1276.      longer than the final value specified.)
  1277.  
  1278.      The || and && operators differ from C's in that, rather than
  1279.      returning  0  or  1,  they  return the last value evaluated.
  1280.      Thus, a portable way to find out the  home  directory  might
  1281.      be:
  1282.  
  1283.           $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  1284.               (getpwuid($<))[7] || die "You're homeless!\n";
  1285.  
  1286.      Along with the literals and variables mentioned earlier, the
  1287.      operations in the following section can serve as terms in an
  1288.      expression.  Some of these operations  take  a  LIST  as  an
  1289.      argument.   Such  a  list  can consist of any combination of
  1290.      scalar arguments or array values; the array values  will  be
  1291.      included  in  the  list  as  if each individual element were
  1292.      interpolated at that point in the  list,  forming  a  longer
  1293.      single-dimensional array value.  Elements of the LIST should
  1294.      be separated by commas.  If an operation is listed both with
  1295.      and  without  parentheses around its arguments, it means you
  1296.      can either use it as a unary operator or as a function call.
  1297.      To  use  it  as  a function call, the next token on the same
  1298.      line must be a left parenthesis.  (There may be  intervening
  1299.      white  space.)  Such a function then has highest precedence,
  1300.      as you would expect from a function.   If  any  token  other
  1301.      than  a  left parenthesis follows, then it is a unary opera-
  1302.      tor, with a precedence depending only on  whether  it  is  a
  1303.      LIST  operator  or  not.   LIST  operators  have lowest pre-
  1304.      cedence.   All  other  unary  operators  have  a  precedence
  1305.      greater  than  relational operators but less than arithmetic
  1306.      operators.  See the section on Precedence.
  1307.  
  1308.      /PATTERN/
  1309.              See m/PATTERN/.
  1310.  
  1311.      ?PATTERN?
  1312.              This is just like the /pattern/ search, except  that
  1313.              it  matches  only  once  between  calls to the reset
  1314.              operator.  This is a useful  optimization  when  you
  1315.              only  want  to see the first occurrence of something
  1316.              in each file of a set of files, for instance.   Only
  1317.              ?? patterns local to the current package are reset.
  1318.  
  1319.      accept(NEWSOCKET,GENERICSOCKET)
  1320.              Does the same thing  that  the  accept  system  call
  1321.              does.   Returns  true  if it succeeded, false other-
  1322.              wise.  See example in section on  Interprocess  Com-
  1323.              munication.
  1324.  
  1325.      alarm(SECONDS)
  1326.      alarm SECONDS
  1327.              Arranges to have a SIGALRM delivered to this process
  1328.              after  the  specified  number  of  seconds (minus 1,
  1329.              actually) have elapsed.  Thus, alarm(15) will  cause
  1330.              a  SIGALRM at some point more than 14 seconds in the
  1331.              future.  Only one timer may  be  counting  at  once.
  1332.              Each  call disables the previous timer, and an argu-
  1333.              ment of 0 may be supplied  to  cancel  the  previous
  1334.              timer  without  starting  a  new  one.  The returned
  1335.              value is the amount of time remaining on the  previ-
  1336.              ous timer.
  1337.  
  1338.      atan2(Y,X)
  1339.              Returns the arctangent of Y/X in the  range  -PI  to
  1340.              PI.
  1341.  
  1342.      bind(SOCKET,NAME)
  1343.              Does the same thing that the bind system call  does.
  1344.              Returns true if it succeeded, false otherwise.  NAME
  1345.              should be a packed address of the  proper  type  for
  1346.              the  socket.  See example in section on Interprocess
  1347.              Communication.
  1348.  
  1349.      binmode(FILEHANDLE)
  1350.      binmode FILEHANDLE
  1351.              Arranges for the file to be read in "binary" mode in
  1352.              operating  systems  that  distinguish between binary
  1353.              and text files.  Files that are not read  in  binary
  1354.              mode  have CR LF sequences translated to LF on input
  1355.              and LF translated to CR LF on output.   Binmode  has
  1356.              no  effect  under Unix.  If FILEHANDLE is an expres-
  1357.              sion, the value is taken as the name of the filehan-
  1358.              dle.
  1359.  
  1360.      caller(EXPR)
  1361.      caller  Returns the context of the current subroutine call:
  1362.  
  1363.                   ($package,$filename,$line) = caller;
  1364.  
  1365.              With EXPR, returns some extra information  that  the
  1366.              debugger  uses to print a stack trace.  The value of
  1367.              EXPR indicates how  many  call  frames  to  go  back
  1368.              before the current one.
  1369.  
  1370.      chdir(EXPR)
  1371.      chdir EXPR
  1372.              Changes the working directory to EXPR, if  possible.
  1373.              If  EXPR  is  omitted,  changes  to  home directory.
  1374.              Returns 1 upon success, 0  otherwise.   See  example
  1375.              under die.
  1376.  
  1377.      chmod(LIST)
  1378.      chmod LIST
  1379.              Changes the permissions of a  list  of  files.   The
  1380.              first  element  of  the  list  must be the numerical
  1381.              mode.  Returns  the  number  of  files  successfully
  1382.              changed.
  1383.  
  1384.                   $cnt = chmod 0755, 'foo', 'bar';
  1385.                   chmod 0755, @executables;
  1386.  
  1387.      chop(LIST)
  1388.      chop(VARIABLE)
  1389.      chop VARIABLE
  1390.      chop    Chops off the last character of a string and returns
  1391.              the  character  chopped.   It's  used  primarily  to
  1392.              remove the newline from the end of an input  record,
  1393.              but  is  much  more efficient than s/\n// because it
  1394.              neither scans nor copies the string.  If VARIABLE is
  1395.              omitted, chops $_.  Example:
  1396.  
  1397.                   while (<>) {
  1398.                        chop;     # avoid \n on last field
  1399.                        @array = split(/:/);
  1400.                        ...
  1401.                   }
  1402.  
  1403.              You can actually chop  anything  that's  an  lvalue,
  1404.              including an assignment:
  1405.  
  1406.                   chop($cwd = `pwd`);
  1407.                   chop($answer = <STDIN>);
  1408.  
  1409.              If you chop a list, each element is  chopped.   Only
  1410.              the value of the last chop is returned.
  1411.  
  1412.      chown(LIST)
  1413.      chown LIST
  1414.              Changes the owner (and group) of a  list  of  files.
  1415.              The  first  two  elements  of  the  list must be the
  1416.              NUMERICAL uid and gid, in that order.   Returns  the
  1417.              number of files successfully changed.
  1418.  
  1419.                   $cnt = chown $uid, $gid, 'foo', 'bar';
  1420.                   chown $uid, $gid, @filenames;
  1421.  
  1422.              Here's an example that looks up non-numeric uids  in
  1423.              the passwd file:
  1424.  
  1425.                   print "User: ";
  1426.                   $user = <STDIN>;
  1427.                   chop($user);
  1428.                   print "Files: "
  1429.                   $pattern = <STDIN>;
  1430.                   chop($pattern);
  1431.                   open(pass, '/etc/passwd')
  1432.                        || die "Can't open passwd: $!\n";
  1433.                   while (<pass>) {
  1434.                        ($login,$pass,$uid,$gid) = split(/:/);
  1435.                        $uid{$login} = $uid;
  1436.                        $gid{$login} = $gid;
  1437.                   }
  1438.                   @ary = <${pattern}>;     # get filenames
  1439.                   if ($uid{$user} eq '') {
  1440.                        die "$user not in passwd file";
  1441.                   }
  1442.                   else {
  1443.                        chown $uid{$user}, $gid{$user}, @ary;
  1444.                   }
  1445.  
  1446.      chroot(FILENAME)
  1447.      chroot FILENAME
  1448.              Does the same as the system call of that  name.   If
  1449.              you  don't  know what it does, don't worry about it.
  1450.              If FILENAME is omitted, does chroot to $_.
  1451.  
  1452.      close(FILEHANDLE)
  1453.      close FILEHANDLE
  1454.              Closes the file or pipe  associated  with  the  file
  1455.              handle.   You  don't have to close FILEHANDLE if you
  1456.              are immediately going to  do  another  open  on  it,
  1457.              since  open will close it for you.  (See open.) How-
  1458.              ever, an explicit close on an input file resets  the
  1459.              line  counter ($.), while the implicit close done by
  1460.              open does not.  Also, closing a pipe will  wait  for
  1461.              the  process  executing  on the pipe to complete, in
  1462.              case you want to look at  the  output  of  the  pipe
  1463.              afterwards.  Closing a pipe explicitly also puts the
  1464.              status value of the command into $?.  Example:
  1465.  
  1466.                   open(OUTPUT, '|sort >foo');   # pipe to sort
  1467.                   ...  # print stuff to output
  1468.                   close OUTPUT;       # wait for sort to finish
  1469.                   open(INPUT, 'foo'); # get sort's results
  1470.  
  1471.              FILEHANDLE may be an expression  whose  value  gives
  1472.              the real filehandle name.
  1473.  
  1474.      closedir(DIRHANDLE)
  1475.      closedir DIRHANDLE
  1476.              Closes a directory opened by opendir().
  1477.  
  1478.      connect(SOCKET,NAME)
  1479.              Does the same thing that  the  connect  system  call
  1480.              does.   Returns  true  if it succeeded, false other-
  1481.              wise.  NAME should  be  a  package  address  of  the
  1482.              proper  type for the socket.  See example in section
  1483.              on Interprocess Communication.
  1484.  
  1485.      cos(EXPR)
  1486.      cos EXPR
  1487.              Returns the cosine of EXPR (expressed  in  radians).
  1488.              If EXPR is omitted takes cosine of $_.
  1489.  
  1490.      crypt(PLAINTEXT,SALT)
  1491.              Encrypts a string exactly like the crypt()  function
  1492.              in  the C library.  Useful for checking the password
  1493.              file for lousy passwords.   Only  the  guys  wearing
  1494.              white hats should do this.
  1495.  
  1496.      dbmclose(ASSOC_ARRAY)
  1497.      dbmclose ASSOC_ARRAY
  1498.              Breaks the binding between a dbm file and an associ-
  1499.              ative  array.   The values remaining in the associa-
  1500.              tive array are meaningless unless you happen to want
  1501.              to  know  what  was  in  the cache for the dbm file.
  1502.              This function is only useful if you have ndbm.
  1503.  
  1504.      dbmopen(ASSOC,DBNAME,MODE)
  1505.              This binds a dbm or  ndbm  file  to  an  associative
  1506.              array.   ASSOC is the name of the associative array.
  1507.              (Unlike normal open, the first  argument  is  NOT  a
  1508.              filehandle,  even though it looks like one).  DBNAME
  1509.              is the name of the database  (without  the  .dir  or
  1510.              .pag extension).  If the database does not exist, it
  1511.              is created with protection  specified  by  MODE  (as
  1512.              modified  by  the  umask).  If your system only sup-
  1513.              ports the older dbm functions, you may perform  only
  1514.              one  dbmopen  in  your  program.  If your system has
  1515.              neither dbm nor ndbm,  calling  dbmopen  produces  a
  1516.              fatal error.
  1517.  
  1518.              Values assigned to the associative  array  prior  to
  1519.              the  dbmopen  are  lost.  A certain number of values
  1520.              from the dbm file are cached in memory.  By  default
  1521.              this number is 64, but you can increase it by preal-
  1522.              locating that number of garbage entries in the asso-
  1523.              ciative array before the dbmopen.  You can flush the
  1524.              cache if necessary with the reset command.
  1525.  
  1526.              If you don't have write access to the dbm file,  you
  1527.              can  only  read associative array variables, not set
  1528.              them.  If you want to test whether  you  can  write,
  1529.              either  use  file tests or try setting a dummy array
  1530.              entry inside an eval, which will trap the error.
  1531.  
  1532.              Note that functions such as keys() and values()  may
  1533.              return  huge  array  values  when  used on large dbm
  1534.              files.  You may prefer to use the each() function to
  1535.              iterate over large dbm files.  Example:
  1536.  
  1537.                   # print out history file offsets
  1538.                   dbmopen(HIST,'/usr/lib/news/history',0666);
  1539.                   while (($key,$val) = each %HIST) {
  1540.                        print $key, ' = ', unpack('L',$val), "\n";
  1541.                   }
  1542.                   dbmclose(HIST);
  1543.  
  1544.      defined(EXPR)
  1545.      defined EXPR
  1546.              Returns a boolean value saying  whether  the  lvalue
  1547.              EXPR  has  a  real  value  or  not.  Many operations
  1548.              return the undefined value under exceptional  condi-
  1549.              tions,  such as end of file, uninitialized variable,
  1550.              system error and such.  This function allows you  to
  1551.              distinguish  between  an undefined null string and a
  1552.              defined  null  string  with  operations  that  might
  1553.              return a real null string, in particular referencing
  1554.              elements of an array.  You may also check to see  if
  1555.              arrays  or  subroutines  exist.   Use  on predefined
  1556.              variables is not  guaranteed  to  produce  intuitive
  1557.              results.  Examples:
  1558.  
  1559.                   print if defined $switch{'D'};
  1560.                   print "$val\n" while defined($val = pop(@ary));
  1561.                   die "Can't readlink $sym: $!"
  1562.                        unless defined($value = readlink $sym);
  1563.                   eval '@foo = ()' if defined(@foo);
  1564.                   die "No XYZ package defined" unless defined %_XYZ;
  1565.                   sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
  1566.  
  1567.              See also undef.
  1568.  
  1569.      delete $ASSOC{KEY}
  1570.              Deletes the specified value from the specified asso-
  1571.              ciative  array.   Returns  the deleted value, or the
  1572.              undefined value if nothing  was  deleted.   Deleting
  1573.              from $ENV{} modifies the environment.  Deleting from
  1574.              an array bound to a dbm file deletes the entry  from
  1575.              the dbm file.
  1576.  
  1577.              The following deletes all the values of an  associa-
  1578.              tive array:
  1579.  
  1580.                   foreach $key (keys %ARRAY) {
  1581.                        delete $ARRAY{$key};
  1582.                   }
  1583.  
  1584.              (But it would be faster to use  the  reset  command.
  1585.              Saying undef %ARRAY is faster yet.)
  1586.  
  1587.      die(LIST)
  1588.      die LIST
  1589.              Outside of an eval, prints  the  value  of  LIST  to
  1590.              STDERR  and  exits  with  the  current  value  of $!
  1591.              (errno).  If $! is 0, exits with the value of ($? >>
  1592.              8)  (`command`  status).   If  ($? >> 8) is 0, exits
  1593.              with 255.  Inside an  eval,  the  error  message  is
  1594.              stuffed  into $@ and the eval is terminated with the
  1595.              undefined value.
  1596.  
  1597.              Equivalent examples:
  1598.  
  1599.                   die "Can't cd to spool: $!\n"
  1600.                        unless chdir '/usr/spool/news';
  1601.  
  1602.                   chdir '/usr/spool/news' || die "Can't cd to spool: $!\n"
  1603.  
  1604.              If the value of EXPR does not end in a newline,  the
  1605.              current script line number and input line number (if
  1606.              any) are also printed, and a  newline  is  supplied.
  1607.              Hint:  sometimes  appending ", stopped" to your mes-
  1608.              sage will cause it to make  better  sense  when  the
  1609.              string  "at  foo line 123" is appended.  Suppose you
  1610.              are running script "canasta".
  1611.  
  1612.                   die "/etc/games is no good";
  1613.                   die "/etc/games is no good, stopped";
  1614.  
  1615.              produce, respectively
  1616.  
  1617.                   /etc/games is no good at canasta line 123.
  1618.                   /etc/games is no good, stopped at canasta line 123.
  1619.  
  1620.              See also exit.
  1621.  
  1622.      do BLOCK
  1623.              Returns  the  value  of  the  last  command  in  the
  1624.              sequence of commands indicated by BLOCK.  When modi-
  1625.              fied by a loop modifier,  executes  the  BLOCK  once
  1626.              before testing the loop condition.  (On other state-
  1627.              ments  the  loop  modifiers  test  the   conditional
  1628.              first.)
  1629.  
  1630.      do SUBROUTINE (LIST)
  1631.              Executes a SUBROUTINE declared by a sub declaration,
  1632.              and   returns  the  value  of  the  last  expression
  1633.              evaluated in SUBROUTINE.  If there is no  subroutine
  1634.              by  that name, produces a fatal error.  (You may use
  1635.              the "defined" operator to determine if a  subroutine
  1636.              exists.)  If you pass arrays as part of LIST you may
  1637.              wish to pass the length of the  array  in  front  of
  1638.              each  array.   (See the section on Subroutines later
  1639.              on.) The parentheses are required to avoid confusion
  1640.              with the "do EXPR" form.
  1641.  
  1642.              SUBROUTINE may also be a single scalar variable,  in
  1643.              which  case the name of the subroutine to execute is
  1644.              taken from the variable.
  1645.  
  1646.              As an alternate (and preferred) form, you may call a
  1647.              subroutine  by prefixing the name with an ampersand:
  1648.              &foo(@args).  If you aren't passing  any  arguments,
  1649.              you  don't have to use parentheses.  If you omit the
  1650.              parentheses, no @_ array is passed  to  the  subrou-
  1651.              tine.   The  &  form is also used to specify subrou-
  1652.              tines to the defined and undef operators:
  1653.  
  1654.                   if (defined &$var) { &$var($parm); undef &$var; }
  1655.  
  1656.      do EXPR Uses the value of EXPR as a  filename  and  executes
  1657.              the contents of the file as a perl script.  Its pri-
  1658.              mary use is to include subroutines from a perl  sub-
  1659.              routine library.
  1660.  
  1661.                   do 'stat.pl';
  1662.  
  1663.              is just like
  1664.  
  1665.                   eval `cat stat.pl`;
  1666.  
  1667.              except that it's more efficient, more concise, keeps
  1668.              track  of  the  current filename for error messages,
  1669.              and searches all the -I libraries if the file  isn't
  1670.              in the current directory (see also the @INC array in
  1671.              Predefined Names).  It's the same, however, in  that
  1672.              it  does reparse the file every time you call it, so
  1673.              if you are going to use the file inside a  loop  you
  1674.              might  prefer to use -P and #include, at the expense
  1675.              of a little more startup time.   (The  main  problem
  1676.              with #include is that cpp doesn't grok # comments--a
  1677.              workaround is to use ";#" for standalone  comments.)
  1678.              Note that the following are NOT equivalent:
  1679.  
  1680.                   do $foo;  # eval a file
  1681.                   do $foo();     # call a subroutine
  1682.  
  1683.              Note that inclusion of library  routines  is  better
  1684.              done with the "require" operator.
  1685.  
  1686.      dump LABEL
  1687.              This causes an immediate core dump.  Primarily  this
  1688.              is  so  that  you can use the undump program to turn
  1689.              your core dump into an executable binary after  hav-
  1690.              ing  initialized all your variables at the beginning
  1691.              of the program.  When the new binary is executed  it
  1692.              will begin by executing a "goto LABEL" (with all the
  1693.              restrictions that goto suffers).  Think of it  as  a
  1694.              goto  with  an  intervening core dump and reincarna-
  1695.              tion.  If LABEL is  omitted,  restarts  the  program
  1696.              from the top.  WARNING: any files opened at the time
  1697.              of the dump will NOT be open any more when the  pro-
  1698.              gram is reincarnated, with possible resulting confu-
  1699.              sion on the part of perl.  See also -u.
  1700.  
  1701.              Example:
  1702.  
  1703.                   #!/usr/bin/perl
  1704.                   require 'getopt.pl';
  1705.                   require 'stat.pl';
  1706.                   %days = (
  1707.                       'Sun',1,
  1708.                       'Mon',2,
  1709.                       'Tue',3,
  1710.                       'Wed',4,
  1711.                       'Thu',5,
  1712.                       'Fri',6,
  1713.                       'Sat',7);
  1714.  
  1715.                   dump QUICKSTART if $ARGV[0] eq '-d';
  1716.  
  1717.                  QUICKSTART:
  1718.                   do Getopt('f');
  1719.  
  1720.      each(ASSOC_ARRAY)
  1721.      each ASSOC_ARRAY
  1722.              Returns a 2 element array consisting of the key  and
  1723.              value for the next value of an associative array, so
  1724.              that you can iterate over it.  Entries are  returned
  1725.              in  an  apparently  random order.  When the array is
  1726.              entirely read, a null array is returned (which  when
  1727.              assigned produces a FALSE (0) value).  The next call
  1728.              to each() after that  will  start  iterating  again.
  1729.              The  iterator  can  be reset only by reading all the
  1730.              elements from the array.  You must  not  modify  the
  1731.              array  while  iterating  over it.  There is a single
  1732.              iterator for each associative array, shared  by  all
  1733.              each(),  keys()  and  values() function calls in the
  1734.              program.  The following prints out your  environment
  1735.              like  the  printenv  program,  only  in  a different
  1736.              order:
  1737.  
  1738.                   while (($key,$value) = each %ENV) {
  1739.                        print "$key=$value\n";
  1740.                   }
  1741.  
  1742.              See also keys() and values().
  1743.  
  1744.      eof(FILEHANDLE)
  1745.      eof()
  1746.      eof     Returns 1 if the next read on FILEHANDLE will return
  1747.              end of file, or if FILEHANDLE is not open.  FILEHAN-
  1748.              DLE may be an expression whose value gives the  real
  1749.              filehandle  name.  (Note that this function actually
  1750.              reads a character and then ungetc's it, so it is not
  1751.              very  useful  in  an  interactive  context.)  An eof
  1752.              without an argument returns the eof status  for  the
  1753.              last file read.  Empty parentheses () may be used to
  1754.              indicate the pseudo file formed of the files  listed
  1755.              on the command line, i.e. eof() is reasonable to use
  1756.              inside a while (<>) loop to detect the end  of  only
  1757.              the  last  file.   Use  eof(ARGV) or eof without the
  1758.              parentheses to test EACH file in a while (<>)  loop.
  1759.              Examples:
  1760.  
  1761.                   # insert dashes just before last line of last file
  1762.                   while (<>) {
  1763.                        if (eof()) {
  1764.                             print "--------------\n";
  1765.                        }
  1766.                        print;
  1767.                   }
  1768.  
  1769.                   # reset line numbering on each input file
  1770.                   while (<>) {
  1771.                        print "$.\t$_";
  1772.                        if (eof) {     # Not eof().
  1773.                             close(ARGV);
  1774.                        }
  1775.                   }
  1776.  
  1777.      eval(EXPR)
  1778.      eval EXPR
  1779.      eval BLOCK
  1780.              EXPR is parsed and executed as if it were  a  little
  1781.              perl  program.  It is executed in the context of the
  1782.              current perl program, so that any variable settings,
  1783.              subroutine  or format definitions remain afterwards.
  1784.              The value returned is the value of the last  expres-
  1785.              sion  evaluated, just as with subroutines.  If there
  1786.              is a syntax error or runtime error, or a die  state-
  1787.              ment  is executed, an undefined value is returned by
  1788.              eval, and $@ is set to the error message.  If  there
  1789.              was  no error, $@ is guaranteed to be a null string.
  1790.              If EXPR is omitted, evaluates $_.  The  final  semi-
  1791.              colon, if any, may be omitted from the expression.
  1792.  
  1793.              Note that, since eval traps otherwise-fatal  errors,
  1794.              it  is  useful  for determining whether a particular
  1795.              feature (such as dbmopen or symlink) is implemented.
  1796.              It  is  also  Perl's  exception  trapping mechanism,
  1797.              where the die operator is used to raise exceptions.
  1798.  
  1799.              If the code to be executed doesn't vary, you may use
  1800.              the  eval-BLOCK form to trap run-time errors without
  1801.              incurring the penalty of recompiling each time.  The
  1802.              error,  if any, is still returned in $@.  Evaluating
  1803.              a  single-quoted  string  (as  EXPR)  has  the  same
  1804.              effect,  except that the eval-EXPR form reports syn-
  1805.              tax errors at run time via  $@,  whereas  the  eval-
  1806.              BLOCK  form  reports  syntax errors at compile time.
  1807.              The eval-EXPR form is optimized  to  eval-BLOCK  the
  1808.              first time it succeeds.  (Since the replacement side
  1809.              of a  substitution  is  considered  a  single-quoted
  1810.              string when you use the e modifier, the same optimi-
  1811.              zation occurs there.)  Examples:
  1812.  
  1813.                   # make divide-by-zero non-fatal
  1814.                   eval { $answer = $a / $b; }; warn $@ if $@;
  1815.  
  1816.                   # optimized to same thing after first use
  1817.                   eval '$answer = $a / $b'; warn $@ if $@;
  1818.  
  1819.                   # a compile-time error
  1820.                   eval { $answer = };
  1821.  
  1822.                   # a run-time error
  1823.                   eval '$answer =';   # sets $@
  1824.  
  1825.      exec(LIST)
  1826.      exec LIST
  1827.              If there is more than one argument in  LIST,  or  if
  1828.              LIST  is  an  array  with more than one value, calls
  1829.              execvp() with the arguments in LIST.   If  there  is
  1830.              only  one  scalar  argument, the argument is checked
  1831.              for shell metacharacters.  If  there  are  any,  the
  1832.              entire  argument is passed to "/bin/sh -c" for pars-
  1833.              ing.  If there are none, the argument is split  into
  1834.              words and passed directly to execvp(), which is more
  1835.              efficient.  Note: exec (and  system)  do  not  flush
  1836.              your  output  buffer,  so  you may need to set $| to
  1837.              avoid lost output.  Examples:
  1838.  
  1839.                   exec '/bin/echo', 'Your arguments are: ', @ARGV;
  1840.                   exec "sort $outfile | uniq";
  1841.  
  1842.              If you don't really want to execute the first  argu-
  1843.              ment, but want to lie to the program you are execut-
  1844.              ing about its own name, you can specify the  program
  1845.              you  actually  want  to  run  by assigning that to a
  1846.              variable and putting the name  of  the  variable  in
  1847.              front  of  the  LIST  without a comma.  (This always
  1848.              forces interpretation of the LIST as a  multi-valued
  1849.              list,  even  if there is only a single scalar in the
  1850.              list.) Example:
  1851.  
  1852.                   $shell = '/bin/csh';
  1853.                   exec $shell '-sh';       # pretend it's a login shell
  1854.  
  1855.      exit EXPR
  1856.              Evaluates  EXPR  and  exits  immediately  with  that
  1857.              value.  Example:
  1858.  
  1859.                   $ans = <STDIN>;
  1860.                   exit 0 if $ans =~ /^[Xx]/;
  1861.  
  1862.              See also die.  If EXPR  is  omitted,  exits  with  0
  1863.              status.
  1864.  
  1865.      exp(EXPR)
  1866.      exp EXPR
  1867.              Returns e to the power of EXPR.  If EXPR is omitted,
  1868.              gives exp($_).
  1869.  
  1870.      fcntl(FILEHANDLE,FUNCTION,SCALAR)
  1871.              Implements the fcntl(2) function.   You'll  probably
  1872.              have to say
  1873.  
  1874.                   require "fcntl.ph"; # probably /usr/local/lib/perl/fcntl.ph
  1875.  
  1876.              first to get the correct function  definitions.   If
  1877.              fcntl.ph  doesn't  exist or doesn't have the correct
  1878.              definitions you'll have to roll your own,  based  on
  1879.              your  C  header files such as <sys/fcntl.h>.  (There
  1880.              is a perl script called h2ph  that  comes  with  the
  1881.              perl  kit which may help you in this.) Argument pro-
  1882.              cessing and  value  return  works  just  like  ioctl
  1883.              below.   Note  that fcntl will produce a fatal error
  1884.              if  used  on  a  machine  that   doesn't   implement
  1885.              fcntl(2).
  1886.  
  1887.      fileno(FILEHANDLE)
  1888.      fileno FILEHANDLE
  1889.              Returns the file descriptor for a filehandle.   Use-
  1890.              ful  for  constructing  bitmaps  for  select().   If
  1891.              FILEHANDLE is an expression, the value is  taken  as
  1892.              the name of the filehandle.
  1893.  
  1894.      flock(FILEHANDLE,OPERATION)
  1895.              Calls flock(2) on FILEHANDLE.  See manual  page  for
  1896.              flock(2)  for definition of OPERATION.  Returns true
  1897.              for success, false on failure.  Will produce a fatal
  1898.              error  if  used  on a machine that doesn't implement
  1899.              flock(2).  Here's a mailbox appender  for  BSD  sys-
  1900.              tems.
  1901.  
  1902.                   $LOCK_SH = 1;
  1903.                   $LOCK_EX = 2;
  1904.                   $LOCK_NB = 4;
  1905.                   $LOCK_UN = 8;
  1906.  
  1907.                   sub lock {
  1908.                       flock(MBOX,$LOCK_EX);
  1909.                       # and, in case someone appended
  1910.                       # while we were waiting...
  1911.                       seek(MBOX, 0, 2);
  1912.                   }
  1913.  
  1914.                   sub unlock {
  1915.                       flock(MBOX,$LOCK_UN);
  1916.                   }
  1917.  
  1918.                   open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
  1919.                        || die "Can't open mailbox: $!";
  1920.  
  1921.                   do lock();
  1922.                   print MBOX $msg,"\n\n";
  1923.                   do unlock();
  1924.  
  1925.      fork    Does a fork() call.  Returns the child  pid  to  the
  1926.              parent  process  and  0 to the child process.  Note:
  1927.              unflushed   buffers   remain   unflushed   in   both
  1928.              processes,  which  means  you  may need to set $| to
  1929.              avoid duplicate output.
  1930.  
  1931.      getc(FILEHANDLE)
  1932.      getc FILEHANDLE
  1933.      getc    Returns the  next  character  from  the  input  file
  1934.              attached to FILEHANDLE, or a null string at EOF.  If
  1935.              FILEHANDLE is omitted, reads from STDIN.
  1936.  
  1937.      getlogin
  1938.              Returns the current login from  /etc/utmp,  if  any.
  1939.              If null, use getpwuid.
  1940.  
  1941.                   $login  =  getlogin  ||  (getpwuid($<))[0]   ||
  1942.              "Somebody";
  1943.  
  1944.      getpeername(SOCKET)
  1945.              Returns the packed sockaddr address of other end  of
  1946.              the SOCKET connection.
  1947.  
  1948.                   # An internet sockaddr
  1949.                   $sockaddr = 'S n a4 x8';
  1950.                   $hersockaddr = getpeername(S);
  1951.                   ($family, $port, $heraddr) =
  1952.                             unpack($sockaddr,$hersockaddr);
  1953.  
  1954.      getpgrp(PID)
  1955.      getpgrp PID
  1956.              Returns the current process group for the  specified
  1957.              PID,  0  for  the  current  process.  Will produce a
  1958.              fatal error if used on a machine that doesn't imple-
  1959.              ment  getpgrp(2).   If EXPR is omitted, returns pro-
  1960.              cess group of current process.
  1961.  
  1962.      getppid Returns the process id of the parent process.
  1963.  
  1964.      getpriority(WHICH,WHO)
  1965.              Returns the current priority for a process,  a  pro-
  1966.              cess  group,  or a user.  (See getpriority(2).) Will
  1967.              produce a fatal error if  used  on  a  machine  that
  1968.              doesn't implement getpriority(2).
  1969.  
  1970.      getgrnam(NAME)
  1971.      gethostbyname(NAME)
  1972.      getnetbyname(NAME)
  1973.      getprotobyname(NAME)
  1974.      getpwuid(UID)
  1975.      getgrgid(GID)
  1976.      getservbyname(NAME,PROTO)
  1977.      gethostbyaddr(ADDR,ADDRTYPE)
  1978.      getnetbyaddr(ADDR,ADDRTYPE)
  1979.      getprotobynumber(NUMBER)
  1980.      getservbyport(PORT,PROTO)
  1981.      getpwent
  1982.      getgrent
  1983.      gethostent
  1984.      getnetent
  1985.      getprotoent
  1986.      getservent
  1987.      setpwent
  1988.      setgrent
  1989.      sethostent(STAYOPEN)
  1990.      setnetent(STAYOPEN)
  1991.      setprotoent(STAYOPEN)
  1992.      setservent(STAYOPEN)
  1993.      endpwent
  1994.      endgrent
  1995.      endhostent
  1996.      endnetent
  1997.      endprotoent
  1998.      endservent
  1999.              These routines perform the same functions  as  their
  2000.              counterparts  in  the  system  library.   The return
  2001.              values from the various get routines are as follows:
  2002.  
  2003.                   ($name,$passwd,$uid,$gid,
  2004.                      $quota,$comment,$gcos,$dir,$shell) = getpw...
  2005.                   ($name,$passwd,$gid,$members) = getgr...
  2006.                   ($name,$aliases,$addrtype,$length,@addrs) = gethost...
  2007.                   ($name,$aliases,$addrtype,$net) = getnet...
  2008.                   ($name,$aliases,$proto) = getproto...
  2009.                   ($name,$aliases,$port,$proto) = getserv...
  2010.  
  2011.              The $members value returned by getgr... is  a  space
  2012.              separated  list of the login names of the members of
  2013.              the group.
  2014.  
  2015.              The @addrs value returned by  the  gethost...  func-
  2016.              tions is a list of the raw addresses returned by the
  2017.              corresponding system library call.  In the  Internet
  2018.              domain,  each address is four bytes long and you can
  2019.              unpack it by saying something like:
  2020.  
  2021.                   ($a,$b,$c,$d) = unpack('C4',$addr[0]);
  2022.  
  2023.      getsockname(SOCKET)
  2024.              Returns the packed sockaddr address of this  end  of
  2025.              the SOCKET connection.
  2026.  
  2027.                   # An internet sockaddr
  2028.                   $sockaddr = 'S n a4 x8';
  2029.                   $mysockaddr = getsockname(S);
  2030.                   ($family, $port, $myaddr) =
  2031.                             unpack($sockaddr,$mysockaddr);
  2032.  
  2033.      getsockopt(SOCKET,LEVEL,OPTNAME)
  2034.              Returns the socket option requested, or undefined if
  2035.              there is an error.
  2036.  
  2037.      gmtime(EXPR)
  2038.      gmtime EXPR
  2039.              Converts a time as returned by the time function  to
  2040.              a  9-element  array  with  the time analyzed for the
  2041.              Greenwich timezone.  Typically used as follows:
  2042.  
  2043.              ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2044.                                            gmtime(time);
  2045.  
  2046.              All array elements are numeric,  and  come  straight
  2047.              out  of  a struct tm.  In particular this means that
  2048.              $mon has the range 0..11 and  $wday  has  the  range
  2049.              0..6.  If EXPR is omitted, does gmtime(time).
  2050.  
  2051.      goto LABEL
  2052.              Finds the statement labeled with LABEL  and  resumes
  2053.              execution  there.   Currently  you  may  only  go to
  2054.              statements in the main body of the program that  are
  2055.              not nested inside a do {} construct.  This statement
  2056.              is not implemented very  efficiently,  and  is  here
  2057.              only  to  make the sed-to-perl translator easier.  I
  2058.              may change its semantics  at  any  time,  consistent
  2059.              with  support for translated sed scripts.  Use it at
  2060.              your own risk.  Better yet, don't use it at all.
  2061.  
  2062.      grep(EXPR,LIST)
  2063.              Evaluates EXPR for each  element  of  LIST  (locally
  2064.              setting  $_  to  each element) and returns the array
  2065.              value consisting of those  elements  for  which  the
  2066.              expression  evaluated to true.  In a scalar context,
  2067.              returns the number of times the expression was true.
  2068.  
  2069.                   @foo = grep(!/^#/, @bar);    # weed out comments
  2070.  
  2071.              Note that, since $_ is a reference  into  the  array
  2072.              value,  it can be used to modify the elements of the
  2073.              array.  While this is useful and supported,  it  can
  2074.              cause  bizarre  results  if  the LIST is not a named
  2075.              array.
  2076.  
  2077.      hex(EXPR)
  2078.      hex EXPR
  2079.              Returns the decimal value of EXPR interpreted as  an
  2080.              hex  string.  (To interpret strings that might start
  2081.              with 0 or 0x see oct().) If EXPR  is  omitted,  uses
  2082.              $_.
  2083.  
  2084.      index(STR,SUBSTR,POSITION)
  2085.      index(STR,SUBSTR)
  2086.              Returns the position  of  the  first  occurrence  of
  2087.              SUBSTR  in STR at or after POSITION.  If POSITION is
  2088.              omitted, starts searching from the beginning of  the
  2089.              string.  The return value is based at 0, or whatever
  2090.              you've set the $[ variable to.  If the substring  is
  2091.              not  found,  returns  one  less than the base, ordi-
  2092.              narily -1.
  2093.  
  2094.      int(EXPR)
  2095.      int EXPR
  2096.              Returns the integer portion of  EXPR.   If  EXPR  is
  2097.              omitted, uses $_.
  2098.  
  2099.      ioctl(FILEHANDLE,FUNCTION,SCALAR)
  2100.              Implements the ioctl(2) function.   You'll  probably
  2101.              have to say
  2102.  
  2103.                   require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.ph
  2104.  
  2105.              first to get the correct function  definitions.   If
  2106.              ioctl.ph  doesn't  exist or doesn't have the correct
  2107.              definitions you'll have to roll your own,  based  on
  2108.              your  C  header files such as <sys/ioctl.h>.  (There
  2109.              is a perl script called h2ph  that  comes  with  the
  2110.              perl kit which may help you in this.) SCALAR will be
  2111.              read and/or written  depending  on  the  FUNCTION--a
  2112.              pointer to the string value of SCALAR will be passed
  2113.              as the third argument of the actual ioctl call.  (If
  2114.              SCALAR  has  no string value but does have a numeric
  2115.              value, that value  will  be  passed  rather  than  a
  2116.              pointer  to  the string value.  To guarantee this to
  2117.              be true, add a 0 to the scalar before using it.) The
  2118.              pack() and unpack() functions are useful for manipu-
  2119.              lating the values of  structures  used  by  ioctl().
  2120.  
  2121.              The  following  example  sets the erase character to
  2122.              DEL.
  2123.  
  2124.                   require 'ioctl.ph';
  2125.                   $sgttyb_t = "ccccs";          # 4 chars and a short
  2126.                   if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
  2127.                        @ary = unpack($sgttyb_t,$sgttyb);
  2128.                        $ary[2] = 127;
  2129.                        $sgttyb = pack($sgttyb_t,@ary);
  2130.                        ioctl(STDIN,$TIOCSETP,$sgttyb)
  2131.                             || die "Can't ioctl: $!";
  2132.                   }
  2133.  
  2134.              The return value of ioctl (and fcntl) is as follows:
  2135.  
  2136.                   if OS returns:           perl returns:
  2137.                     -1                       undefined value
  2138.                     0                        string "0 but true"
  2139.                     anything else            that number
  2140.  
  2141.              Thus perl returns  true  on  success  and  false  on
  2142.              failure,  yet  you  can  still  easily determine the
  2143.              actual value returned by the operating system:
  2144.  
  2145.                   ($retval = ioctl(...)) || ($retval = -1);
  2146.                   printf "System returned %d\n", $retval;
  2147.  
  2148.      join(EXPR,LIST)
  2149.      join(EXPR,ARRAY)
  2150.              Joins the separate strings of LIST or ARRAY  into  a
  2151.              single  string with fields separated by the value of
  2152.              EXPR, and returns the string.  Example:
  2153.  
  2154.              $_ = join(':',
  2155.                        $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  2156.  
  2157.              See split.
  2158.  
  2159.      keys(ASSOC_ARRAY)
  2160.      keys ASSOC_ARRAY
  2161.              Returns a normal array consisting of all the keys of
  2162.              the  named associative array.  The keys are returned
  2163.              in an apparently random order, but it  is  the  same
  2164.              order as either the values() or each() function pro-
  2165.              duces (given that the associative array has not been
  2166.              modified).   Here  is  yet another way to print your
  2167.              environment:
  2168.  
  2169.                   @keys = keys %ENV;
  2170.                   @values = values %ENV;
  2171.                   while ($#keys >= 0) {
  2172.                        print pop(@keys), '=', pop(@values), "\n";
  2173.                   }
  2174.  
  2175.              or how about sorted by key:
  2176.  
  2177.                   foreach $key (sort(keys %ENV)) {
  2178.                        print $key, '=', $ENV{$key}, "\n";
  2179.                   }
  2180.  
  2181.      kill(LIST)
  2182.      kill LIST
  2183.              Sends a signal to a list of  processes.   The  first
  2184.              element  of  the  list  must  be the signal to send.
  2185.              Returns the number of  processes  successfully  sig-
  2186.              naled.
  2187.  
  2188.                   $cnt = kill 1, $child1, $child2;
  2189.                   kill 9, @goners;
  2190.  
  2191.              If the signal  is  negative,  kills  process  groups
  2192.              instead of processes.  (On System V, a negative pro-
  2193.              cess number  will  also  kill  process  groups,  but
  2194.              that's  not  portable.) You may use a signal name in
  2195.              quotes.
  2196.  
  2197.      last LABEL
  2198.      last    The last command is like the break  statement  in  C
  2199.              (as used in loops); it immediately exits the loop in
  2200.              question.  If the  LABEL  is  omitted,  the  command
  2201.              refers  to  the  innermost enclosing loop.  The con-
  2202.              tinue block, if any, is not executed:
  2203.  
  2204.                   line: while (<STDIN>) {
  2205.                        last line if /^$/;  # exit when done with header
  2206.                        ...
  2207.                   }
  2208.  
  2209.      length(EXPR)
  2210.      length EXPR
  2211.              Returns the length in characters  of  the  value  of
  2212.              EXPR.  If EXPR is omitted, returns length of $_.
  2213.  
  2214.      link(OLDFILE,NEWFILE)
  2215.              Creates a new filename linked to the  old  filename.
  2216.  
  2217.              Returns 1 for success, 0 otherwise.
  2218.  
  2219.      listen(SOCKET,QUEUESIZE)
  2220.              Does the same thing  that  the  listen  system  call
  2221.              does.   Returns  true  if it succeeded, false other-
  2222.              wise.  See example in section on  Interprocess  Com-
  2223.              munication.
  2224.  
  2225.      local(LIST)
  2226.              Declares the listed variables to  be  local  to  the
  2227.              enclosing  block, subroutine, eval or "do".  All the
  2228.              listed elements must be legal lvalues.  This  opera-
  2229.              tor  works  by  saving  the  current values of those
  2230.              variables in LIST on a hidden  stack  and  restoring
  2231.              them  upon  exiting  the  block, subroutine or eval.
  2232.              This means that called subroutines can  also  refer-
  2233.              ence  the  local  variable,  but not the global one.
  2234.              The LIST may be assigned to if desired, which allows
  2235.              you to initialize your local variables.  (If no ini-
  2236.              tializer is given for a particular variable,  it  is
  2237.              created  with  an undefined value.) Commonly this is
  2238.              used to name the parameters to a subroutine.   Exam-
  2239.              ples:
  2240.  
  2241.                   sub RANGEVAL {
  2242.                        local($min, $max, $thunk) = @_;
  2243.                        local($result) = '';
  2244.                        local($i);
  2245.  
  2246.                        # Presumably $thunk makes reference to $i
  2247.  
  2248.                        for ($i = $min; $i < $max; $i++) {
  2249.                             $result .= eval $thunk;
  2250.                        }
  2251.  
  2252.                        $result;
  2253.                   }
  2254.  
  2255.                   if ($sw eq '-v') {
  2256.                       # init local array with global array
  2257.                       local(@ARGV) = @ARGV;
  2258.                       unshift(@ARGV,'echo');
  2259.                       system @ARGV;
  2260.                   }
  2261.                   # @ARGV restored
  2262.  
  2263.                   # temporarily add to digits associative array
  2264.                   if ($base12) {
  2265.                        # (NOTE: not claiming this is efficient!)
  2266.                        local(%digits) = (%digits,'t',10,'e',11);
  2267.                        do parse_num();
  2268.                   }
  2269.  
  2270.              Note that local() is a run-time command, and so gets
  2271.              executed  every  time  through a loop, using up more
  2272.              stack storage each time until it's all  released  at
  2273.              once when the loop is exited.
  2274.  
  2275.      localtime(EXPR)
  2276.      localtime EXPR
  2277.              Converts a time as returned by the time function  to
  2278.              a  9-element  array  with  the time analyzed for the
  2279.              local timezone.  Typically used as follows:
  2280.  
  2281.              ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2282.                                            localtime(time);
  2283.  
  2284.              All array elements are numeric,  and  come  straight
  2285.              out  of  a struct tm.  In particular this means that
  2286.              $mon has the range 0..11 and  $wday  has  the  range
  2287.              0..6.  If EXPR is omitted, does localtime(time).
  2288.  
  2289.      log(EXPR)
  2290.      log EXPR
  2291.              Returns logarithm (base e)  of  EXPR.   If  EXPR  is
  2292.              omitted, returns log of $_.
  2293.  
  2294.      lstat(FILEHANDLE)
  2295.      lstat FILEHANDLE
  2296.      lstat(EXPR)
  2297.      lstat SCALARVARIABLE
  2298.              Does the same thing  as  the  stat()  function,  but
  2299.              stats  a  symbolic link instead of the file the sym-
  2300.              bolic link points to.  If symbolic links  are  unim-
  2301.              plemented on your system, a normal stat is done.
  2302.  
  2303.      m/PATTERN/gio
  2304.      /PATTERN/gio
  2305.              Searches a string for a pattern match,  and  returns
  2306.              true  (1)  or false ('').  If no string is specified
  2307.              via  the  =~  or  !~  operator,  the  $_  string  is
  2308.              searched.  (The string specified with =~ need not be
  2309.              an lvalue--it may be the  result  of  an  expression
  2310.              evaluation,   but   remember  the  =~  binds  rather
  2311.              tightly.) See also the section  on  Regular  Expres-
  2312.              sions.
  2313.  
  2314.              If / is  the  delimiter  then  the  initial  'm'  is
  2315.              optional.   With  the  'm'  you  can use any pair of
  2316.              non-alphanumeric characters as delimiters.  This  is
  2317.              particularly  useful  for  matching  Unix path names
  2318.              that contain '/'.  If the final  delimiter  is  fol-
  2319.              lowed  by  the  optional letter 'i', the matching is
  2320.              done in a case-insensitive manner.  PATTERN may con-
  2321.              tain  references  to scalar variables, which will be
  2322.              interpolated (and the pattern recompiled) every time
  2323.              the  pattern search is evaluated.  (Note that $) and
  2324.              $| may not be interpolated because  they  look  like
  2325.              end-of-string  tests.) If you want such a pattern to
  2326.              be compiled only once, add an "o" after the trailing
  2327.              delimiter.   This avoids expensive run-time recompi-
  2328.              lations, and is useful when the value you are inter-
  2329.              polating  won't  change over the life of the script.
  2330.              If the PATTERN evaluates to a null string, the  most
  2331.              recent   successful   regular   expression  is  used
  2332.              instead.
  2333.  
  2334.              If used in a context that requires an array value, a
  2335.              pattern  match  returns  an  array consisting of the
  2336.              subexpressions matched by  the  parentheses  in  the
  2337.              pattern, i.e. ($1, $2, $3...).  It does NOT actually
  2338.              set $1, $2, etc. in this case, nor does it  set  $+,
  2339.              $`,  $&  or $'.  If the match fails, a null array is
  2340.              returned.  If the match succeeds, but there were  no
  2341.              parentheses, an array value of (1) is returned.
  2342.  
  2343.              Examples:
  2344.  
  2345.                  open(tty, '/dev/tty');
  2346.                  <tty> =~ /^y/i && do foo();    # do foo if desired
  2347.  
  2348.                  if (/Version: *([0-9.]*)/) { $version = $1; }
  2349.  
  2350.                  next if m#^/usr/spool/uucp#;
  2351.  
  2352.                  # poor man's grep
  2353.                  $arg = shift;
  2354.                  while (<>) {
  2355.                       print if /$arg/o;    # compile only once
  2356.                  }
  2357.  
  2358.                  if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
  2359.  
  2360.              This last example splits $foo  into  the  first  two
  2361.              words  and  the  remainder  of the line, and assigns
  2362.              those three fields to $F1, $F2 and $Etc.  The condi-
  2363.              tional  is true if any variables were assigned, i.e.
  2364.              if the pattern matched.
  2365.  
  2366.              The   "g"   modifier   specifies   global    pattern
  2367.              matching--that   is,   matching  as  many  times  as
  2368.              possible within the string.  How it behaves  depends
  2369.              on  the  context.  In an array context, it returns a
  2370.              list of  all  the  substrings  matched  by  all  the
  2371.              parentheses in the regular expression.  If there are
  2372.              no parentheses, it returns a list of all the matched
  2373.              strings,  as  if  there  were parentheses around the
  2374.              whole pattern.  In a  scalar  context,  it  iterates
  2375.              through  the  string,  returning  TRUE  each time it
  2376.              matches, and FALSE when it eventually  runs  out  of
  2377.              matches.   (In  other  words,  it remembers where it
  2378.              left off last time and restarts the search  at  that
  2379.              point.)   It presumes that you have not modified the
  2380.              string since the last match.  Modifying  the  string
  2381.              between  matches  may  result in undefined behavior.
  2382.              (You can actually get away with  in-place  modifica-
  2383.              tions  via substr() that do not change the length of
  2384.              the entire string.  In general, however, you  should
  2385.              be using s///g for such modifications.)  Examples:
  2386.  
  2387.                   # array context
  2388.                   ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
  2389.  
  2390.                   # scalar context
  2391.                   $/ = 1; $* = 1;
  2392.                   while ($paragraph = <>) {
  2393.                       while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
  2394.                        $sentences++;
  2395.                       }
  2396.                   }
  2397.                   print "$sentences\n";
  2398.  
  2399.      mkdir(FILENAME,MODE)
  2400.              Creates the directory specified  by  FILENAME,  with
  2401.              permissions   specified  by  MODE  (as  modified  by
  2402.              umask).  If it succeeds it returns 1,  otherwise  it
  2403.              returns 0 and sets $! (errno).
  2404.  
  2405.      msgctl(ID,CMD,ARG)
  2406.              Calls the System V IPC function msgctl.  If  CMD  is
  2407.              &IPC_STAT,  then  ARG  must be a variable which will
  2408.              hold the returned msqid_ds structure.  Returns  like
  2409.              ioctl:  the  undefined value for error, "0 but true"
  2410.              for zero, or the actual return value otherwise.
  2411.  
  2412.      msgget(KEY,FLAGS)
  2413.              Calls the System V IPC function msgget.  Returns the
  2414.              message queue id, or the undefined value if there is
  2415.              an error.
  2416.  
  2417.      msgsnd(ID,MSG,FLAGS)
  2418.              Calls the System V IPC function msgsnd to  send  the
  2419.              message MSG to the message queue ID.  MSG must begin
  2420.              with the long integer message  type,  which  may  be
  2421.              created with pack("L", $type).  Returns true if suc-
  2422.              cessful, or false if there is an error.
  2423.  
  2424.      msgrcv(ID,VAR,SIZE,TYPE,FLAGS)
  2425.              Calls the System V IPC function msgrcv to receive  a
  2426.              message from message queue ID into variable VAR with
  2427.              a maximum message size of SIZE.  Note that if a mes-
  2428.              sage is received, the message type will be the first
  2429.              thing in VAR, and the maximum length of VAR is  SIZE
  2430.              plus  the size of the message type.  Returns true if
  2431.              successful, or false if there is an error.
  2432.  
  2433.      next LABEL
  2434.      next    The next command is like the continue  statement  in
  2435.              C; it starts the next iteration of the loop:
  2436.  
  2437.                   line: while (<STDIN>) {
  2438.                        next line if /^#/;  # discard comments
  2439.                        ...
  2440.                   }
  2441.  
  2442.              Note that if there were  a  continue  block  on  the
  2443.              above,  it  would  get  executed  even  on discarded
  2444.              lines.  If the LABEL is omitted, the command  refers
  2445.              to the innermost enclosing loop.
  2446.  
  2447.      oct(EXPR)
  2448.      oct EXPR
  2449.              Returns the decimal value of EXPR interpreted as  an
  2450.              octal  string.   (If  EXPR happens to start off with
  2451.              0x, interprets it as a hex string instead.) The fol-
  2452.              lowing  will  handle  decimal,  octal and hex in the
  2453.              standard notation:
  2454.  
  2455.                   $val = oct($val) if $val =~ /^0/;
  2456.  
  2457.              If EXPR is omitted, uses $_.
  2458.  
  2459.      open(FILEHANDLE,EXPR)
  2460.      open(FILEHANDLE)
  2461.      open FILEHANDLE
  2462.              Opens the file whose filename is given by EXPR,  and
  2463.              associates  it with FILEHANDLE.  If FILEHANDLE is an
  2464.              expression, its value is used as  the  name  of  the
  2465.              real  filehandle  wanted.   If  EXPR is omitted, the
  2466.              scalar variable of the same name as  the  FILEHANDLE
  2467.              contains  the filename.  If the filename begins with
  2468.              "<" or nothing, the file is opened  for  input.   If
  2469.              the filename begins with ">", the file is opened for
  2470.              output.  If the filename begins with ">>", the  file
  2471.              is  opened  for  appending.   (You  can put a '+' in
  2472.              front of the '>' or '<' to indicate  that  you  want
  2473.              both  read  and  write  access  to the file.) If the
  2474.              filename begins with "|",  the  filename  is  inter-
  2475.              preted  as a command to which output is to be piped,
  2476.              and if the filename ends with a "|", the filename is
  2477.              interpreted  as  command  which  pipes  input to us.
  2478.              (You may not have a command that pipes both  in  and
  2479.              out.) Opening '-' opens STDIN and opening '>-' opens
  2480.              STDOUT.  Open returns  non-zero  upon  success,  the
  2481.              undefined  value  otherwise.  If the open involved a
  2482.              pipe, the return value happens to be the pid of  the
  2483.              subprocess.  Examples:
  2484.  
  2485.                   $article = 100;
  2486.                   open article || die "Can't find article $article: $!\n";
  2487.                   while (<article>) {...
  2488.  
  2489.                   open(LOG, '>>/usr/spool/news/twitlog');
  2490.                                       # (log is reserved)
  2491.  
  2492.                   open(article, "caesar <$article |");
  2493.                                       # decrypt article
  2494.  
  2495.                   open(extract, "|sort >/tmp/Tmp$$");
  2496.                                       # $$ is our process#
  2497.  
  2498.                   # process argument list of files along with any includes
  2499.  
  2500.                   foreach $file (@ARGV) {
  2501.                        do process($file, 'fh00');    # no pun intended
  2502.                   }
  2503.  
  2504.                   sub process {
  2505.                        local($filename, $input) = @_;
  2506.                        $input++;      # this is a string increment
  2507.                        unless (open($input, $filename)) {
  2508.                             print STDERR "Can't open $filename: $!\n";
  2509.                             return;
  2510.                        }
  2511.                        while (<$input>) {       # note use of indirection
  2512.                             if (/^#include "(.*)"/) {
  2513.                                  do process($1, $input);
  2514.                                  next;
  2515.                             }
  2516.                             ...       # whatever
  2517.  
  2518.                        }
  2519.                   }
  2520.  
  2521.              You may also, in the Bourne shell tradition, specify
  2522.              an  EXPR beginning with ">&", in which case the rest
  2523.              of the string  is  interpreted  as  the  name  of  a
  2524.              filehandle (or file descriptor, if numeric) which is
  2525.              to be duped and opened.  You may use & after >,  >>,
  2526.              <,  +>,  +>>  and  +<.   The mode you specify should
  2527.              match the mode of the original filehandle.  Here  is
  2528.              a  script that saves, redirects, and restores STDOUT
  2529.              and STDERR:
  2530.  
  2531.                   #!/usr/bin/perl
  2532.                   open(SAVEOUT, ">&STDOUT");
  2533.                   open(SAVEERR, ">&STDERR");
  2534.  
  2535.                   open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  2536.                   open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  2537.  
  2538.                   select(STDERR); $| = 1;       # make unbuffered
  2539.                   select(STDOUT); $| = 1;       # make unbuffered
  2540.  
  2541.                   print STDOUT "stdout 1\n";    # this works for
  2542.                   print STDERR "stderr 1\n";    # subprocesses too
  2543.  
  2544.                   close(STDOUT);
  2545.                   close(STDERR);
  2546.  
  2547.                   open(STDOUT, ">&SAVEOUT");
  2548.                   open(STDERR, ">&SAVEERR");
  2549.  
  2550.                   print STDOUT "stdout 2\n";
  2551.                   print STDERR "stderr 2\n";
  2552.  
  2553.              If you open a pipe on the command "-",  i.e.  either
  2554.              "|-"  or  "-|", then there is an implicit fork done,
  2555.              and the return value of open is the pid of the child
  2556.              within  the  parent  process, and 0 within the child
  2557.              process.  (Use defined($pid)  to  determine  if  the
  2558.              open  was  successful.)  The filehandle behaves nor-
  2559.              mally for the parent, but i/o to that filehandle  is
  2560.              piped from/to the STDOUT/STDIN of the child process.
  2561.              In the child process the filehandle  isn't  opened--
  2562.              i/o  happens from/to the new STDOUT or STDIN.  Typi-
  2563.              cally this is used like the normal piped  open  when
  2564.              you  want to exercise more control over just how the
  2565.              pipe command gets executed, such  as  when  you  are
  2566.              running setuid, and don't want to have to scan shell
  2567.              commands for metacharacters.   The  following  pairs
  2568.              are more or less equivalent:
  2569.  
  2570.                   open(FOO, "|tr '[a-z]' '[A-Z]'");
  2571.                   open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
  2572.  
  2573.                   open(FOO, "cat -n '$file'|");
  2574.                   open(FOO, "-|") || exec 'cat', '-n', $file;
  2575.  
  2576.              Explicitly closing any piped filehandle  causes  the
  2577.              parent  process to wait for the child to finish, and
  2578.              returns the status value in $?.  Note: on any opera-
  2579.              tion  which  may do a fork, unflushed buffers remain
  2580.              unflushed in both processes,  which  means  you  may
  2581.              need to set $| to avoid duplicate output.
  2582.  
  2583.              The filename that is passed to open will have  lead-
  2584.              ing  and  trailing  whitespace deleted.  In order to
  2585.              open a file with arbitrary weird characters  in  it,
  2586.              it's  necessary  to protect any leading and trailing
  2587.              whitespace thusly:
  2588.  
  2589.                      $file =~ s#^(\s)#./$1#;
  2590.                      open(FOO, "< $file\0");
  2591.  
  2592.      opendir(DIRHANDLE,EXPR)
  2593.              Opens a directory named EXPR for processing by read-
  2594.              dir(),   telldir(),   seekdir(),   rewinddir()   and
  2595.              closedir().  Returns true if successful.  DIRHANDLEs
  2596.              have their own namespace separate from FILEHANDLEs.
  2597.  
  2598.      ord(EXPR)
  2599.      ord EXPR
  2600.              Returns the numeric ascii value of the first charac-
  2601.              ter of EXPR.  If EXPR is omitted, uses $_.
  2602.  
  2603.      pack(TEMPLATE,LIST)
  2604.              Takes an array or list of values and packs it into a
  2605.              binary  structure,  returning  the string containing
  2606.              the structure.  The TEMPLATE is a sequence of  char-
  2607.              acters  that  give  the order and type of values, as
  2608.              follows:
  2609.  
  2610.                   A    An ascii string, will be space padded.
  2611.                   a    An ascii string, will be null padded.
  2612.                   c    A signed char value.
  2613.                   C    An unsigned char value.
  2614.                   s    A signed short value.
  2615.                   S    An unsigned short value.
  2616.                   i    A signed integer value.
  2617.                   I    An unsigned integer value.
  2618.                   l    A signed long value.
  2619.                   L    An unsigned long value.
  2620.                   n    A short in "network" order.
  2621.                   N    A long in "network" order.
  2622.                   f    A single-precision float in the native format.
  2623.                   d    A double-precision float in the native format.
  2624.                   p    A pointer to a string.
  2625.                   v    A short in "VAX" (little-endian) order.
  2626.                   V    A long in "VAX" (little-endian) order.
  2627.                   x    A null byte.
  2628.                   X    Back up a byte.
  2629.                   @    Null fill to absolute position.
  2630.                   u    A uuencoded string.
  2631.                   b    A bit string (ascending bit order, like vec()).
  2632.                   B    A bit string (descending bit order).
  2633.                   h    A hex string (low nybble first).
  2634.                   H    A hex string (high nybble first).
  2635.  
  2636.              Each letter may optionally be followed by  a  number
  2637.              which  gives  a repeat count.  With all types except
  2638.              "a", "A", "b", "B", "h" and "H", the  pack  function
  2639.              will  gobble up that many values from the LIST.  A *
  2640.              for the repeat count means to use however many items
  2641.              are  left.   The  "a"  and "A" types gobble just one
  2642.              value, but pack it as a string of length count, pad-
  2643.              ding  with  nulls  or  spaces  as  necessary.  (When
  2644.              unpacking, "A" strips trailing spaces and nulls, but
  2645.              "a" does not.) Likewise, the "b" and "B" fields pack
  2646.              a string that many  bits  long.   The  "h"  and  "H"
  2647.              fields  pack  a string that many nybbles long.  Real
  2648.              numbers (floats  and  doubles)  are  in  the  native
  2649.              machine  format  only;  due  to  the multiplicity of
  2650.              floating formats around, and the lack of a  standard
  2651.              "network"  representation,  no  facility  for inter-
  2652.              change has been made.  This means that packed float-
  2653.              ing  point  data  written  on one machine may not be
  2654.              readable on another - even if both use IEEE floating
  2655.              point  arithmetic  (as the endian-ness of the memory
  2656.              representation is not part of the IEEE spec).   Note
  2657.              that  perl  uses  doubles internally for all numeric
  2658.              calculation, and converting from double -> float  ->
  2659.              double   will   lose   precision  (i.e.  unpack("f",
  2660.              pack("f", $foo)) will not in general equal $foo).
  2661.              Examples:
  2662.  
  2663.                   $foo = pack("cccc",65,66,67,68);
  2664.                   # foo eq "ABCD"
  2665.                   $foo = pack("c4",65,66,67,68);
  2666.                   # same thing
  2667.  
  2668.                   $foo = pack("ccxxcc",65,66,67,68);
  2669.                   # foo eq "AB\0\0CD"
  2670.  
  2671.                   $foo = pack("s2",1,2);
  2672.  
  2673.                   # "\1\0\2\0" on little-endian
  2674.                   # "\0\1\0\2" on big-endian
  2675.  
  2676.                   $foo = pack("a4","abcd","x","y","z");
  2677.                   # "abcd"
  2678.  
  2679.                   $foo = pack("aaaa","abcd","x","y","z");
  2680.                   # "axyz"
  2681.  
  2682.                   $foo = pack("a14","abcdefg");
  2683.                   # "abcdefg\0\0\0\0\0\0\0"
  2684.  
  2685.                   $foo = pack("i9pl", gmtime);
  2686.                   # a real struct tm (on my system anyway)
  2687.  
  2688.                   sub bintodec {
  2689.                       unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  2690.                   }
  2691.              The same template may generally also be used in  the
  2692.              unpack function.
  2693.  
  2694.      pipe(READHANDLE,WRITEHANDLE)
  2695.              Opens a pair of connected pipes like the correspond-
  2696.              ing  system call.  Note that if you set up a loop of
  2697.              piped processes, deadlock can occur unless  you  are
  2698.              very  careful.   In addition, note that perl's pipes
  2699.              use stdio buffering, so you may need to  set  $|  to
  2700.              flush your WRITEHANDLE after each command, depending
  2701.              on   the   application.    [Requires   version   3.0
  2702.              patchlevel 9.]
  2703.  
  2704.      pop(ARRAY)
  2705.      pop ARRAY
  2706.              Pops and returns the last value of the array,  shor-
  2707.              tening the array by 1.  Has the same effect as
  2708.  
  2709.                   $tmp = $ARRAY[$#ARRAY--];
  2710.  
  2711.              If there are no elements in the array,  returns  the
  2712.              undefined value.
  2713.  
  2714.      print(FILEHANDLE LIST)
  2715.      print(LIST)
  2716.      print FILEHANDLE LIST
  2717.      print LIST
  2718.      print   Prints  a  string  or  a  comma-separated  list   of
  2719.              strings.     Returns    non-zero    if   successful.
  2720.              FILEHANDLE may be a scalar variable name,  in  which
  2721.              case  the variable contains the name of the filehan-
  2722.              dle, thus  introducing  one  level  of  indirection.
  2723.              (NOTE:  If  FILEHANDLE  is  a  variable and the next
  2724.              token is a term, it  may  be  misinterpreted  as  an
  2725.              operator  unless  you  interpose  a  + or put parens
  2726.              around the arguments.)  If  FILEHANDLE  is  omitted,
  2727.              prints by default to standard output (or to the last
  2728.              selected output channel--see select()).  If LIST  is
  2729.              also  omitted,  prints  $_  to  STDOUT.   To set the
  2730.              default  output  channel  to  something  other  than
  2731.              STDOUT use the select operation.  Note that, because
  2732.              print  takes  a  LIST,  anything  in  the  LIST   is
  2733.              evaluated  in  an  array context, and any subroutine
  2734.              that you call will have one or more of  its  expres-
  2735.              sions  evaluated in an array context.  Also be care-
  2736.              ful not to follow the  print  keyword  with  a  left
  2737.              parenthesis  unless you want the corresponding right
  2738.              parenthesis  to  terminate  the  arguments  to   the
  2739.              print--interpose  a  +  or put parens around all the
  2740.              arguments.
  2741.  
  2742.      printf(FILEHANDLE LIST)
  2743.      printf(LIST)
  2744.      printf FILEHANDLE LIST
  2745.      printf LIST
  2746.              Equivalent to a "print FILEHANDLE sprintf(LIST)".
  2747.  
  2748.      push(ARRAY,LIST)
  2749.              Treats ARRAY (@ is optional) as a stack, and  pushes
  2750.              the  values  of  LIST  onto  the  end of ARRAY.  The
  2751.              length of ARRAY increases by  the  length  of  LIST.
  2752.              Has the same effect as
  2753.  
  2754.                  for $value (LIST) {
  2755.                       $ARRAY[++$#ARRAY] = $value;
  2756.                  }
  2757.  
  2758.              but is more efficient.
  2759.  
  2760.      q/STRING/
  2761.      qq/STRING/
  2762.      qx/STRING/
  2763.              These are not really functions, but simply syntactic
  2764.              sugar  to let you avoid putting too many backslashes
  2765.              into quoted strings.  The q operator is  a  general-
  2766.              ized single quote, and the qq operator a generalized
  2767.              double quote.  The  qx  operator  is  a  generalized
  2768.              backquote.   Any  non-alphanumeric  delimiter can be
  2769.              used in place of /, including newline.  If the  del-
  2770.              imiter  is  an  opening  bracket or parenthesis, the
  2771.              final delimiter will be  the  corresponding  closing
  2772.              bracket  or  parenthesis.   (Embedded occurrences of
  2773.              the  closing  bracket  need  to  be  backslashed  as
  2774.              usual.) Examples:
  2775.  
  2776.                   $foo = q!I said, "You said, 'She said it.'"!;
  2777.                   $bar = q('This is it.');
  2778.                   $today = qx{ date };
  2779.                   $_ .= qq
  2780.              *** The previous line contains the naughty word "$&".\n
  2781.                        if /(ibm|apple|awk)/;      # :-)
  2782.  
  2783.      rand(EXPR)
  2784.      rand EXPR
  2785.      rand    Returns a random fractional number between 0 and the
  2786.              value  of  EXPR.  (EXPR should be positive.) If EXPR
  2787.              is omitted, returns a value between 0  and  1.   See
  2788.              also srand().
  2789.  
  2790.      read(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  2791.      read(FILEHANDLE,SCALAR,LENGTH)
  2792.              Attempts to read LENGTH bytes of data into  variable
  2793.              SCALAR  from  the specified FILEHANDLE.  Returns the
  2794.              number of bytes actually read, or undef if there was
  2795.              an  error.   SCALAR  will  be grown or shrunk to the
  2796.              length actually read.  An OFFSET may be specified to
  2797.              place  the  read  data  at some other place than the
  2798.              beginning of the  string.   This  call  is  actually
  2799.              implemented  in terms of stdio's fread call.  To get
  2800.              a true read system call, see sysread.
  2801.  
  2802.      readdir(DIRHANDLE)
  2803.      readdir DIRHANDLE
  2804.              Returns the next directory  entry  for  a  directory
  2805.              opened  by  opendir().  If used in an array context,
  2806.              returns all the rest of the entries  in  the  direc-
  2807.              tory.   If  there  are  no  more entries, returns an
  2808.              undefined value in a scalar context or a  null  list
  2809.              in an array context.
  2810.  
  2811.      readlink(EXPR)
  2812.      readlink EXPR
  2813.              Returns the value of a symbolic  link,  if  symbolic
  2814.              links are implemented.  If not, gives a fatal error.
  2815.              If there is some system error, returns the undefined
  2816.              value and sets $! (errno).  If EXPR is omitted, uses
  2817.              $_.
  2818.  
  2819.      recv(SOCKET,SCALAR,LEN,FLAGS)
  2820.              Receives a message on a socket.  Attempts to receive
  2821.              LENGTH  bytes  of data into variable SCALAR from the
  2822.              specified SOCKET filehandle.  Returns the address of
  2823.              the  sender,  or  the  undefined value if there's an
  2824.              error.  SCALAR will be grown or shrunk to the length
  2825.              actually  read.   Takes the same flags as the system
  2826.              call of the same name.
  2827.  
  2828.      redo LABEL
  2829.      redo    The redo command restarts  the  loop  block  without
  2830.              evaluating  the  conditional  again.   The  continue
  2831.              block, if any, is not executed.   If  the  LABEL  is
  2832.              omitted, the command refers to the innermost enclos-
  2833.              ing loop.  This command is normally used by programs
  2834.              that  want  to lie to themselves about what was just
  2835.              input:
  2836.  
  2837.                   # a simpleminded Pascal comment stripper
  2838.                   # (warning: assumes no { or } in strings)
  2839.                   line: while (<STDIN>) {
  2840.                        while (s|({.*}.*){.*}|$1 |) {}
  2841.                        s|{.*}| |;
  2842.                        if (s|{.*| |) {
  2843.                             $front = $_;
  2844.                             while (<STDIN>) {
  2845.                                  if (/}/) {     # end of comment?
  2846.                                       s|^|$front{|;
  2847.                                       redo line;
  2848.                                  }
  2849.                             }
  2850.                        }
  2851.                        print;
  2852.                   }
  2853.  
  2854.      rename(OLDNAME,NEWNAME)
  2855.              Changes the name of a file.  Returns 1 for  success,
  2856.              0  otherwise.  Will not work across filesystem boun-
  2857.              daries.
  2858.  
  2859.      require(EXPR)
  2860.      require EXPR
  2861.      require Includes the library file specified by EXPR,  or  by
  2862.              $_  if  EXPR is not supplied.  Has semantics similar
  2863.              to the following subroutine:
  2864.  
  2865.                   sub require {
  2866.                       local($filename) = @_;
  2867.                       return 1 if $INC{$filename};
  2868.                       local($realfilename,$result);
  2869.                       ITER: {
  2870.                        foreach $prefix (@INC) {
  2871.                            $realfilename = "$prefix/$filename";
  2872.                            if (-f $realfilename) {
  2873.                             $result = do $realfilename;
  2874.                             last ITER;
  2875.                            }
  2876.                        }
  2877.                        die "Can't find $filename in \@INC";
  2878.                       }
  2879.                       die $@ if $@;
  2880.                       die "$filename did not return true value" unless $result;
  2881.                       $INC{$filename} = $realfilename;
  2882.                       $result;
  2883.                   }
  2884.  
  2885.              Note that the file will not be included twice  under
  2886.              the same specified name.
  2887.  
  2888.      reset(EXPR)
  2889.      reset EXPR
  2890.      reset   Generally used in a continue block at the end  of  a
  2891.              loop  to  clear  variables  and reset ?? searches so
  2892.              that they work again.  The expression is interpreted
  2893.              as  a list of single characters (hyphens allowed for
  2894.              ranges).  All variables and  arrays  beginning  with
  2895.              one  of  those  letters  are reset to their pristine
  2896.              state.  If  the  expression  is  omitted,  one-match
  2897.              searches (?pattern?) are reset to match again.  Only
  2898.              resets variables or searches in the current package.
  2899.              Always returns 1.  Examples:
  2900.  
  2901.                  reset 'X';      # reset all X variables
  2902.                  reset 'a-z';    # reset lower case variables
  2903.                  reset;          # just reset ?? searches
  2904.  
  2905.              Note:  resetting  "A-Z"  is  not  recommended  since
  2906.              you'll wipe out your ARGV and ENV arrays.
  2907.  
  2908.              The use of reset on dbm associative arrays does  not
  2909.              change  the  dbm file.  (It does, however, flush any
  2910.              entries cached by perl, which may be useful  if  you
  2911.              are sharing the dbm file.  Then again, maybe not.)
  2912.  
  2913.      return LIST
  2914.              Returns from a subroutine with the value  specified.
  2915.              (Note that a subroutine can automatically return the
  2916.              value of the last expression evaluated.  That's  the
  2917.              preferred method--use of an explicit return is a bit
  2918.              slower.)
  2919.  
  2920.      reverse(LIST)
  2921.      reverse LIST
  2922.              In an array context, returns an array value consist-
  2923.              ing  of  the elements of LIST in the opposite order.
  2924.              In a scalar context, returns a string value consist-
  2925.              ing of the bytes of the first element of LIST in the
  2926.              opposite order.
  2927.  
  2928.      rewinddir(DIRHANDLE)
  2929.      rewinddir DIRHANDLE
  2930.              Sets the current position to the  beginning  of  the
  2931.              directory for the readdir() routine on DIRHANDLE.
  2932.  
  2933.      rindex(STR,SUBSTR,POSITION)
  2934.      rindex(STR,SUBSTR)
  2935.              Works just like index except  that  it  returns  the
  2936.              position  of  the  LAST occurrence of SUBSTR in STR.
  2937.              If  POSITION  is   specified,   returns   the   last
  2938.              occurrence at or before that position.
  2939.  
  2940.      rmdir(FILENAME)
  2941.      rmdir FILENAME
  2942.              Deletes the directory specified by FILENAME if it is
  2943.              empty.   If  it  succeeds it returns 1, otherwise it
  2944.              returns 0 and sets $! (errno).  If FILENAME is omit-
  2945.              ted, uses $_.
  2946.  
  2947.      s/PATTERN/REPLACEMENT/gieo
  2948.              Searches a string  for  a  pattern,  and  if  found,
  2949.              replaces  that pattern with the replacement text and
  2950.              returns the number of substitutions made.  Otherwise
  2951.              it  returns  false (0).  The "g" is optional, and if
  2952.              present, indicates that all occurrences of the  pat-
  2953.              tern  are to be replaced.  The "i" is also optional,
  2954.              and if present, indicates that  matching  is  to  be
  2955.              done  in  a  case-insensitive  manner.   The  "e" is
  2956.              likewise optional, and if  present,  indicates  that
  2957.              the  replacement  string  is  to  be evaluated as an
  2958.              expression  rather  than  just  as  a  double-quoted
  2959.              string.   Any non-alphanumeric delimiter may replace
  2960.              the slashes; if single quotes are used, no interpre-
  2961.              tation  is  done  on  the  replacement string (the e
  2962.              modifier overrides this, however); if backquotes are
  2963.              used, the replacement string is a command to execute
  2964.              whose output will be used as the actual  replacement
  2965.              text.   If  no  string is specified via the =~ or !~
  2966.              operator, the $_ string is  searched  and  modified.
  2967.              (The string specified with =~ must be a scalar vari-
  2968.              able, an array element, or an assignment to  one  of
  2969.              those,  i.e. an lvalue.) If the pattern contains a $
  2970.              that looks like a variable rather  than  an  end-of-
  2971.              string  test, the variable will be interpolated into
  2972.              the pattern at run-time.  If you only want the  pat-
  2973.              tern  compiled  once  the first time the variable is
  2974.              interpolated, add an "o" at the end.  If the PATTERN
  2975.              evaluates to a null string, the most recent success-
  2976.              ful regular expression is used  instead.   See  also
  2977.              the section on regular expressions.  Examples:
  2978.  
  2979.                  s/\bgreen\b/mauve/g;      # don't change wintergreen
  2980.  
  2981.                  $path =~ s|/usr/bin|/usr/local/bin|;
  2982.  
  2983.                  s/Login: $foo/Login: $bar/; # run-time pattern
  2984.  
  2985.                  ($foo = $bar) =~ s/bar/foo/;
  2986.  
  2987.                  $_ = 'abc123xyz';
  2988.                  s/\d+/$&*2/e;        # yields 'abc246xyz'
  2989.                  s/\d+/sprintf("%5d",$&)/e;     # yields 'abc  246xyz'
  2990.                  s/\w/$& x 2/eg;      # yields 'aabbcc  224466xxyyzz'
  2991.  
  2992.                  s/([^ ]*) *([^ ]*)/$2 $1/;     # reverse 1st two fields
  2993.  
  2994.              (Note the use of $ instead of \ in the last example.
  2995.              See section on Regular Expressions.)
  2996.  
  2997.      scalar(EXPR)
  2998.              Forces EXPR to be interpreted in  a  scalar  context
  2999.              and returns the value of EXPR.
  3000.  
  3001.      seek(FILEHANDLE,POSITION,WHENCE)
  3002.              Randomly positions the file pointer for  FILEHANDLE,
  3003.              just like the fseek() call of stdio.  FILEHANDLE may
  3004.              be an expression whose value gives the name  of  the
  3005.              filehandle.  Returns 1 upon success, 0 otherwise.
  3006.  
  3007.      seekdir(DIRHANDLE,POS)
  3008.              Sets the current position for the readdir()  routine
  3009.              on  DIRHANDLE.   POS  must  be  a  value returned by
  3010.              telldir().  Has  the  same  caveats  about  possible
  3011.              directory  compaction  as  the  corresponding system
  3012.              library routine.
  3013.  
  3014.      select(FILEHANDLE)
  3015.      select  Returns the currently selected filehandle.  Sets the
  3016.              current default filehandle for output, if FILEHANDLE
  3017.              is supplied.  This has two effects: first,  a  write
  3018.              or a print without a filehandle will default to this
  3019.              FILEHANDLE.  Second, references to variables related
  3020.              to  output  will  refer to this output channel.  For
  3021.              example, if you have to set the top of  form  format
  3022.              for  more  than one output channel, you might do the
  3023.              following:
  3024.  
  3025.                   select(REPORT1);
  3026.                   $^ = 'report1_top';
  3027.                   select(REPORT2);
  3028.                   $^ = 'report2_top';
  3029.  
  3030.              FILEHANDLE may be an expression  whose  value  gives
  3031.              the name of the actual filehandle.  Thus:
  3032.  
  3033.                   $oldfh = select(STDERR); $| = 1; select($oldfh);
  3034.  
  3035.      select(RBITS,WBITS,EBITS,TIMEOUT)
  3036.              This calls the select system call with the  bitmasks
  3037.              specified,  which  can be constructed using fileno()
  3038.              and vec(), along these lines:
  3039.  
  3040.                   $rin = $win = $ein = '';
  3041.                   vec($rin,fileno(STDIN),1) = 1;
  3042.                   vec($win,fileno(STDOUT),1) = 1;
  3043.                   $ein = $rin | $win;
  3044.  
  3045.              If you want to select on many filehandles you  might
  3046.              wish to write a subroutine:
  3047.  
  3048.                   sub fhbits {
  3049.                       local(@fhlist) = split(' ',$_[0]);
  3050.                       local($bits);
  3051.                       for (@fhlist) {
  3052.                        vec($bits,fileno($_),1) = 1;
  3053.                       }
  3054.                       $bits;
  3055.                   }
  3056.                   $rin = &fhbits('STDIN TTY SOCK');
  3057.  
  3058.              The usual idiom is:
  3059.  
  3060.                   ($nfound,$timeleft) =
  3061.                     select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  3062.  
  3063.              or to block until something becomes ready:
  3064.  
  3065.                   $nfound = select($rout=$rin, $wout=$win,
  3066.                                  $eout=$ein, undef);
  3067.  
  3068.              Any of the bitmasks can also be undef.  The timeout,
  3069.              if  specified,  is  in  seconds,  which may be frac-
  3070.              tional.  NOTE: not all implementations  are  capable
  3071.              of  returning  the  $timeleft.   If not, they always
  3072.              return $timeleft equal to the supplied $timeout.
  3073.  
  3074.      semctl(ID,SEMNUM,CMD,ARG)
  3075.              Calls the System V IPC function semctl.  If  CMD  is
  3076.              &IPC_STAT  or  &GETALL,  then ARG must be a variable
  3077.              which will hold the returned semid_ds  structure  or
  3078.              semaphore  value  array.   Returns  like  ioctl: the
  3079.              undefined value for error, "0 but true" for zero, or
  3080.              the actual return value otherwise.
  3081.  
  3082.      semget(KEY,NSEMS,SIZE,FLAGS)
  3083.              Calls the System V IPC function semget.  Returns the
  3084.              semaphore  id, or the undefined value if there is an
  3085.              error.
  3086.  
  3087.      semop(KEY,OPSTRING)
  3088.              Calls the System V IPC  function  semop  to  perform
  3089.              semaphore  operations such as signaling and waiting.
  3090.              OPSTRING must be a packed array of semop structures.
  3091.              Each   semop   structure   can   be  generated  with
  3092.              'pack("sss",  $semnum,  $semop,   $semflag)'.    The
  3093.              number  of  semaphore  operations  is implied by the
  3094.              length of OPSTRING.  Returns true if successful,  or
  3095.              false if there is an error.  As an example, the fol-
  3096.              lowing code waits on semaphore $semnum of  semaphore
  3097.              id $semid:
  3098.  
  3099.                   $semop = pack("sss", $semnum, -1, 0);
  3100.                   die "Semaphore trouble: $!\n" unless semop($semid, $semop);
  3101.  
  3102.              To signal the semaphore, replace "-1" with "1".
  3103.  
  3104.      send(SOCKET,MSG,FLAGS,TO)
  3105.      send(SOCKET,MSG,FLAGS)
  3106.              Sends a message on a socket.  Takes the  same  flags
  3107.              as the system call of the same name.  On unconnected
  3108.              sockets you must specify a destination to  send  TO.
  3109.              Returns  the number of characters sent, or the unde-
  3110.              fined value if there is an error.
  3111.  
  3112.      setpgrp(PID,PGRP)
  3113.              Sets the current process  group  for  the  specified
  3114.              PID,  0  for  the  current  process.  Will produce a
  3115.              fatal error if used on a machine that doesn't imple-
  3116.              ment setpgrp(2).
  3117.  
  3118.      setpriority(WHICH,WHO,PRIORITY)
  3119.              Sets the current priority for a process,  a  process
  3120.              group,  or  a user.  (See setpriority(2).) Will pro-
  3121.              duce a fatal error if used on a machine that doesn't
  3122.              implement setpriority(2).
  3123.  
  3124.      setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
  3125.              Sets the socket option requested.  Returns undefined
  3126.              if  there  is  an error.  OPTVAL may be specified as
  3127.              undef if you don't want to pass an argument.
  3128.  
  3129.      shift(ARRAY)
  3130.      shift ARRAY
  3131.      shift   Shifts the first value of the array off and  returns
  3132.              it,  shortening the array by 1 and moving everything
  3133.              down.  If  there  are  no  elements  in  the  array,
  3134.              returns  the  undefined value.  If ARRAY is omitted,
  3135.              shifts the @ARGV array in the main program, and  the
  3136.              @_  array in subroutines.  (This is determined lexi-
  3137.              cally.)  See  also  unshift(),  push()  and   pop().
  3138.              Shift()  and unshift() do the same thing to the left
  3139.              end of an array that push()  and  pop()  do  to  the
  3140.              right end.
  3141.  
  3142.      shmctl(ID,CMD,ARG)
  3143.              Calls the System V IPC function shmctl.  If  CMD  is
  3144.              &IPC_STAT,  then  ARG  must be a variable which will
  3145.              hold the returned shmid_ds structure.  Returns  like
  3146.              ioctl:  the  undefined value for error, "0 but true"
  3147.              for zero, or the actual return value otherwise.
  3148.  
  3149.      shmget(KEY,SIZE,FLAGS)
  3150.              Calls the System V IPC function shmget.  Returns the
  3151.              shared  memory segment id, or the undefined value if
  3152.              there is an error.
  3153.  
  3154.      shmread(ID,VAR,POS,SIZE)
  3155.      shmwrite(ID,STRING,POS,SIZE)
  3156.              Reads or writes the System V shared  memory  segment
  3157.              ID  starting  at  position  POS  for  size  SIZE  by
  3158.              attaching to it, copying in/out, and detaching  from
  3159.              it.  When reading, VAR must be a variable which will
  3160.              hold the data read.  When writing, if STRING is  too
  3161.              long,  only  SIZE  bytes  are used; if STRING is too
  3162.              short, nulls are written to  fill  out  SIZE  bytes.
  3163.              Return  true  if successful, or false if there is an
  3164.              error.
  3165.  
  3166.      shutdown(SOCKET,HOW)
  3167.              Shuts down a socket connection in the  manner  indi-
  3168.              cated  by  HOW, which has the same interpretation as
  3169.              in the system call of the same name.
  3170.  
  3171.      sin(EXPR)
  3172.      sin EXPR
  3173.              Returns the sine of EXPR (expressed in radians).  If
  3174.              EXPR is omitted, returns sine of $_.
  3175.  
  3176.      sleep(EXPR)
  3177.      sleep EXPR
  3178.      sleep   Causes the script to sleep for EXPR seconds, or for-
  3179.              ever  if no EXPR.  May be interrupted by sending the
  3180.              process a SIGALRM.  Returns the  number  of  seconds
  3181.              actually slept.  You probably cannot mix alarm() and
  3182.              sleep() calls, since sleep()  is  often  implemented
  3183.              using alarm().
  3184.  
  3185.      socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
  3186.              Opens a socket of the specified kind and attaches it
  3187.              to filehandle SOCKET.  DOMAIN, TYPE and PROTOCOL are
  3188.              specified the same as for the  system  call  of  the
  3189.              same name.  You may need to run h2ph on sys/socket.h
  3190.              to get the proper values handy  in  a  perl  library
  3191.              file.   Return  true if successful.  See the example
  3192.              in the section on Interprocess Communication.
  3193.  
  3194.      socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
  3195.              Creates an unnamed pair of sockets in the  specified
  3196.              domain,  of  the  specified  type.  DOMAIN, TYPE and
  3197.              PROTOCOL are specified the same as  for  the  system
  3198.              call  of  the same name.  If unimplemented, yields a
  3199.              fatal error.  Return true if successful.
  3200.  
  3201.      sort(SUBROUTINE LIST)
  3202.      sort(LIST)
  3203.      sort SUBROUTINE LIST
  3204.      sort BLOCK LIST
  3205.      sort LIST
  3206.              Sorts the LIST and returns the sorted  array  value.
  3207.              Nonexistent  values  of arrays are stripped out.  If
  3208.              SUBROUTINE or BLOCK is omitted,  sorts  in  standard
  3209.              string  comparison  order.   If SUBROUTINE is speci-
  3210.              fied, gives the name of a subroutine that returns an
  3211.              integer  less  than,  equal  to,  or greater than 0,
  3212.              depending on how the elements of the array are to be
  3213.              ordered.   (The  <=> and cmp operators are extremely
  3214.              useful in such routines.) SUBROUTINE may be a scalar
  3215.              variable  name, in which case the value provides the
  3216.              name of the subroutine to use.  In place of  a  SUB-
  3217.              ROUTINE   name,  you  can  provide  a  BLOCK  as  an
  3218.              anonymous, in-line sort subroutine.
  3219.  
  3220.              In the interests of efficiency  the  normal  calling
  3221.              code for subroutines is bypassed, with the following
  3222.              effects: the subroutine may not be a recursive  sub-
  3223.              routine,  and  the  two  elements to be compared are
  3224.              passed into the subroutine not via @_ but as $a  and
  3225.              $b  (see  example below).  They are passed by refer-
  3226.              ence so don't modify $a and $b.
  3227.  
  3228.              Examples:
  3229.  
  3230.                   # sort lexically
  3231.                   @articles = sort @files;
  3232.  
  3233.                   # same thing, but with explicit sort routine
  3234.                   @articles = sort {$a cmp $b;} @files;
  3235.  
  3236.                   # same thing in reversed order
  3237.                   @articles = sort {$b cmp $a;} @files;
  3238.  
  3239.                   # sort numerically ascending
  3240.                   @articles = sort {$a <=> $b;} @files;
  3241.  
  3242.                   # sort numerically descending
  3243.                   @articles = sort {$b <=> $a;} @files;
  3244.  
  3245.                   # sort using explicit subroutine name
  3246.                   sub byage {
  3247.                       $age{$a} <=> $age{$b};    # presuming integers
  3248.                   }
  3249.                   @sortedclass = sort byage @class;
  3250.  
  3251.                   sub reverse { $b cmp $a; }
  3252.                   @harry = ('dog','cat','x','Cain','Abel');
  3253.                   @george = ('gone','chased','yz','Punished','Axed');
  3254.                   print sort @harry;
  3255.                        # prints AbelCaincatdogx
  3256.                   print sort reverse @harry;
  3257.                        # prints xdogcatCainAbel
  3258.                   print sort @george, 'to', @harry;
  3259.                        # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  3260.  
  3261.      splice(ARRAY,OFFSET,LENGTH,LIST)
  3262.      splice(ARRAY,OFFSET,LENGTH)
  3263.      splice(ARRAY,OFFSET)
  3264.              Removes the elements designated by OFFSET and LENGTH
  3265.              from  an  array, and replaces them with the elements
  3266.              of LIST, if any.  Returns the elements removed  from
  3267.              the array.  The array grows or shrinks as necessary.
  3268.              If LENGTH is omitted, removes everything from OFFSET
  3269.              onward.   The following equivalencies hold (assuming
  3270.              $[ == 0):
  3271.  
  3272.                   push(@a,$x,$y)                splice(@a,$#a+1,0,$x,$y)
  3273.                   pop(@a)                       splice(@a,-1)
  3274.                   shift(@a)                     splice(@a,0,1)
  3275.                   unshift(@a,$x,$y)             splice(@a,0,0,$x,$y)
  3276.                   $a[$x] = $y                   splice(@a,$x,1,$y);
  3277.  
  3278.              Example, assuming array lengths are passed before arrays:
  3279.  
  3280.                   sub aeq { # compare two array values
  3281.                        local(@a) = splice(@_,0,shift);
  3282.                        local(@b) = splice(@_,0,shift);
  3283.                        return 0 unless @a == @b;     # same len?
  3284.                        while (@a) {
  3285.                            return 0 if pop(@a) ne pop(@b);
  3286.                        }
  3287.                        return 1;
  3288.                   }
  3289.                   if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  3290.  
  3291.      split(/PATTERN/,EXPR,LIMIT)
  3292.      split(/PATTERN/,EXPR)
  3293.      split(/PATTERN/)
  3294.      split   Splits a  string  into  an  array  of  strings,  and
  3295.              returns  it.   (If  not in an array context, returns
  3296.              the number of fields found and splits  into  the  @_
  3297.              array.   (In  an  array  context,  you can force the
  3298.              split into @_ by using ?? as the pattern delimiters,
  3299.              but  it  still returns the array value.)) If EXPR is
  3300.              omitted, splits the $_ string.  If PATTERN  is  also
  3301.              omitted,  splits  on  whitespace (/[ \t\n]+/).  Any-
  3302.              thing matching PATTERN is taken to  be  a  delimiter
  3303.              separating the fields.  (Note that the delimiter may
  3304.              be longer than one character.) If  LIMIT  is  speci-
  3305.              fied,  splits  into  no  more  than that many fields
  3306.              (though it may  split  into  fewer).   If  LIMIT  is
  3307.              unspecified,   trailing  null  fields  are  stripped
  3308.              (which potential users of pop()  would  do  well  to
  3309.              remember).   A pattern matching the null string (not
  3310.              to be confused with a null pattern //, which is just
  3311.              one  member  of  the set of patterns matching a null
  3312.              string) will split the value of EXPR  into  separate
  3313.              characters  at  each point it matches that way.  For
  3314.              example:
  3315.  
  3316.                   print join(':', split(/ */, 'hi there'));
  3317.  
  3318.              produces the output 'h:i:t:h:e:r:e'.
  3319.  
  3320.              The LIMIT parameter can be used to partially split a
  3321.              line
  3322.  
  3323.                   ($login, $passwd, $remainder) = split(/:/, $_, 3);
  3324.  
  3325.              (When assigning to a list, if LIMIT is omitted, perl
  3326.              supplies a LIMIT one larger than the number of vari-
  3327.              ables in the list, to avoid unnecessary  work.   For
  3328.              the  list  above LIMIT would have been 4 by default.
  3329.              In time critical applications it behooves you not to
  3330.              split into more fields than you really need.)
  3331.  
  3332.              If  the  PATTERN  contains  parentheses,  additional
  3333.              array  elements  are created from each matching sub-
  3334.              string in the delimiter.
  3335.  
  3336.                   split(/([,-])/,"1-10,20");
  3337.  
  3338.              produces the array value
  3339.  
  3340.                   (1,'-',10,',',20)
  3341.  
  3342.              The  pattern  /PATTERN/  may  be  replaced  with  an
  3343.              expression to specify patterns that vary at runtime.
  3344.              (To  do   runtime   compilation   only   once,   use
  3345.              /$variable/o.) As a special case, specifying a space
  3346.              (' ') will split on white space just as  split  with
  3347.              no  arguments does, but leading white space does NOT
  3348.              produce a null first field.  Thus, split(' ') can be
  3349.              used  to  emulate  awk's  default  behavior, whereas
  3350.              split(/ /) will give you as many null initial fields
  3351.              as there are leading spaces.
  3352.  
  3353.              Example:
  3354.  
  3355.                   open(passwd, '/etc/passwd');
  3356.                   while (<passwd>) {
  3357.                        ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  3358.                             = split(/:/);
  3359.                        ...
  3360.                   }
  3361.  
  3362.              (Note that $shell above will still have a newline on
  3363.              it.  See chop().) See also join.
  3364.  
  3365.      sprintf(FORMAT,LIST)
  3366.              Returns a string formatted by the usual printf  con-
  3367.              ventions.  The * character is not supported.
  3368.  
  3369.      sqrt(EXPR)
  3370.      sqrt EXPR
  3371.              Return the square root of EXPR.  If EXPR is omitted,
  3372.              returns square root of $_.
  3373.  
  3374.      srand(EXPR)
  3375.      srand EXPR
  3376.              Sets the random number seed for the  rand  operator.
  3377.              If EXPR is omitted, does srand(time).
  3378.  
  3379.      stat(FILEHANDLE)
  3380.      stat FILEHANDLE
  3381.      stat(EXPR)
  3382.      stat SCALARVARIABLE
  3383.              Returns a 13-element array giving the statistics for
  3384.              a  file,  either  the file opened via FILEHANDLE, or
  3385.              named by EXPR.  Typically used as follows:
  3386.  
  3387.                  ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  3388.                     $atime,$mtime,$ctime,$blksize,$blocks)
  3389.                         = stat($filename);
  3390.  
  3391.              If stat is passed the special filehandle  consisting
  3392.              of  an  underline,  no stat is done, but the current
  3393.              contents of the stat structure from the last stat or
  3394.              filetest are returned.  Example:
  3395.  
  3396.                   if (-x $file && (($d) = stat(_)) && $d < 0) {
  3397.                        print "$file is executable NFS file\n";
  3398.                   }
  3399.  
  3400.              (This only works on machines for  which  the  device
  3401.              number is negative under NFS.)
  3402.  
  3403.      study(SCALAR)
  3404.      study SCALAR
  3405.      study   Takes extra time to study SCALAR ($_ if unspecified)
  3406.              in anticipation of doing many pattern matches on the
  3407.              string before it is next modified.  This may or  may
  3408.              not save time, depending on the nature and number of
  3409.              patterns you are searching on, and on the  distribu-
  3410.              tion  of  character  frequencies in the string to be
  3411.              searched--you probably want to compare runtimes with
  3412.              and  without  it  to  see  which runs faster.  Those
  3413.              loops which scan for  many  short  constant  strings
  3414.              (including  the  constant parts of more complex pat-
  3415.              terns) will benefit most.  You  may  have  only  one
  3416.              study  active  at  a  time--if you study a different
  3417.              scalar the first is  "unstudied".   (The  way  study
  3418.              works  is  this: a linked list of every character in
  3419.              the string to be searched is made, so we  know,  for
  3420.              example,  where  all  the  'k' characters are.  From
  3421.              each  search  string,  the   rarest   character   is
  3422.              selected, based on some static frequency tables con-
  3423.              structed from some  C  programs  and  English  text.
  3424.              Only those places that contain this "rarest" charac-
  3425.              ter are examined.)
  3426.  
  3427.              For example, here is a loop which inserts index pro-
  3428.              ducing  entries before any line containing a certain
  3429.              pattern:
  3430.  
  3431.                   while (<>) {
  3432.                        study;
  3433.                        print ".IX foo\n" if /\bfoo\b/;
  3434.                        print ".IX bar\n" if /\bbar\b/;
  3435.                        print ".IX blurfl\n" if /\bblurfl\b/;
  3436.                        ...
  3437.                        print;
  3438.                   }
  3439.  
  3440.              In searching for /\bfoo\b/, only those locations  in
  3441.              $_  that  contain 'f' will be looked at, because 'f'
  3442.              is rarer than 'o'.  In general, this is  a  big  win
  3443.              except  in pathological cases.  The only question is
  3444.              whether it saves you more time than it took to build
  3445.              the linked list in the first place.
  3446.  
  3447.              Note that if you have to look for strings  that  you
  3448.              don't  know  till  runtime,  you can build an entire
  3449.              loop as a string and eval that to avoid  recompiling
  3450.              all your patterns all the time.  Together with unde-
  3451.              fining $/ to input entire files as one record,  this
  3452.              can be very fast, often faster than specialized pro-
  3453.              grams like fgrep.  The following  scans  a  list  of
  3454.              files  (@files)  for  a  list of words (@words), and
  3455.              prints out the names of those files that  contain  a
  3456.              match:
  3457.  
  3458.                   $search = 'while (<>) { study;';
  3459.                   foreach $word (@words) {
  3460.                       $search .= "++\$seen{\$ARGV} if /\b$word\b/;\n";
  3461.                   }
  3462.                   $search .= "}";
  3463.                   @ARGV = @files;
  3464.                   undef $/;
  3465.                   eval $search;       # this screams
  3466.                   $/ = "\n";          # put back to normal input delim
  3467.                   foreach $file (sort keys(%seen)) {
  3468.                       print $file, "\n";
  3469.                   }
  3470.  
  3471.      substr(EXPR,OFFSET,LEN)
  3472.      substr(EXPR,OFFSET)
  3473.              Extracts a substring out of  EXPR  and  returns  it.
  3474.              First  character  is at offset 0, or whatever you've
  3475.              set $[ to.  If OFFSET is negative, starts  that  far
  3476.              from  the  end  of  the  string.  If LEN is omitted,
  3477.              returns everything to the end of  the  string.   You
  3478.              can use the substr() function as an lvalue, in which
  3479.              case EXPR must be an lvalue.  If  you  assign  some-
  3480.              thing  shorter than LEN, the string will shrink, and
  3481.              if you assign something longer than LEN, the  string
  3482.              will grow to accommodate it.  To keep the string the
  3483.              same length you may need to pad or chop  your  value
  3484.              using sprintf().
  3485.  
  3486.      symlink(OLDFILE,NEWFILE)
  3487.              Creates a new filename symbolically  linked  to  the
  3488.              old  filename.   Returns 1 for success, 0 otherwise.
  3489.              On systems that don't support symbolic  links,  pro-
  3490.              duces a fatal error at run time.  To check for that,
  3491.              use eval:
  3492.  
  3493.                   $symlink_exists = (eval 'symlink("","");', $@ eq '');
  3494.  
  3495.      syscall(LIST)
  3496.      syscall LIST
  3497.              Calls the system call specified as the first element
  3498.              of the list, passing the remaining elements as argu-
  3499.              ments to the system call.   If  unimplemented,  pro-
  3500.              duces  a fatal error.  The arguments are interpreted
  3501.              as follows: if a  given  argument  is  numeric,  the
  3502.              argument  is  passed as an int.  If not, the pointer
  3503.              to the string value is passed.  You are  responsible
  3504.              to make sure a string is pre-extended long enough to
  3505.              receive any result that  might  be  written  into  a
  3506.              string.   If your integer arguments are not literals
  3507.              and have never been interpreted in  a  numeric  con-
  3508.              text, you may need to add 0 to them to force them to
  3509.              look like numbers.
  3510.  
  3511.                   require 'syscall.ph';         # may need to run h2ph
  3512.                   syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9);
  3513.  
  3514.      sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3515.      sysread(FILEHANDLE,SCALAR,LENGTH)
  3516.              Attempts to read LENGTH bytes of data into  variable
  3517.              SCALAR from the specified FILEHANDLE, using the sys-
  3518.              tem call read(2).  It bypasses stdio, so mixing this
  3519.              with  other  kinds  of  reads  may  cause confusion.
  3520.              Returns the number of bytes actually read, or  undef
  3521.              if  there  was  an  error.   SCALAR will be grown or
  3522.              shrunk to the length actually read.  An  OFFSET  may
  3523.              be  specified  to  place the read data at some other
  3524.              place than the beginning of the string.
  3525.  
  3526.      system(LIST)
  3527.      system LIST
  3528.              Does exactly the same thing as  "exec  LIST"  except
  3529.              that  a  fork  is done first, and the parent process
  3530.              waits for the child process to complete.  Note  that
  3531.              argument  processing  varies depending on the number
  3532.              of arguments.  The return value is the  exit  status
  3533.              of  the  program as returned by the wait() call.  To
  3534.              get the actual exit value divide by 256.   See  also
  3535.              exec.
  3536.  
  3537.      syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3538.      syswrite(FILEHANDLE,SCALAR,LENGTH)
  3539.              Attempts to write LENGTH bytes of data from variable
  3540.              SCALAR to the specified FILEHANDLE, using the system
  3541.              call write(2).  It bypasses stdio,  so  mixing  this
  3542.              with prints may cause confusion.  Returns the number
  3543.              of bytes actually written, or undef if there was  an
  3544.              error.  An OFFSET may be specified to place the read
  3545.              data at some other place than the beginning  of  the
  3546.              string.
  3547.  
  3548.      tell(FILEHANDLE)
  3549.      tell FILEHANDLE
  3550.      tell    Returns the current file  position  for  FILEHANDLE.
  3551.              FILEHANDLE  may  be  an expression whose value gives
  3552.              the name of the actual filehandle.  If FILEHANDLE is
  3553.              omitted, assumes the file last read.
  3554.  
  3555.      telldir(DIRHANDLE)
  3556.      telldir DIRHANDLE
  3557.              Returns the current position of the  readdir()  rou-
  3558.              tines on DIRHANDLE.  Value may be given to seekdir()
  3559.              to access a particular location in a directory.  Has
  3560.              the same caveats about possible directory compaction
  3561.              as the corresponding system library routine.
  3562.  
  3563.      time    Returns  the  number  of  non-leap   seconds   since
  3564.              00:00:00 UTC, January 1, 1970.  Suitable for feeding
  3565.              to gmtime() and localtime().
  3566.  
  3567.      times   Returns a four-element array  giving  the  user  and
  3568.              system  times,  in seconds, for this process and the
  3569.              children of this process.
  3570.  
  3571.                  ($user,$system,$cuser,$csystem) = times;
  3572.  
  3573.      tr/SEARCHLIST/REPLACEMENTLIST/cds
  3574.      y/SEARCHLIST/REPLACEMENTLIST/cds
  3575.              Translates all occurrences of the  characters  found
  3576.              in  the search list with the corresponding character
  3577.              in the replacement list.  It returns the  number  of
  3578.              characters  replaced  or  deleted.   If no string is
  3579.              specified via the =~ or !~ operator, the  $_  string
  3580.              is  translated.   (The string specified with =~ must
  3581.              be a  scalar  variable,  an  array  element,  or  an
  3582.              assignment to one of those, i.e. an lvalue.) For sed
  3583.              devotees, y is provided as a synonym for tr.
  3584.  
  3585.              If the c modifier is specified, the SEARCHLIST char-
  3586.              acter  set  is  complemented.   If the d modifier is
  3587.              specified, any characters  specified  by  SEARCHLIST
  3588.              that  are  not found in REPLACEMENTLIST are deleted.
  3589.              (Note that this is slightly more flexible  than  the
  3590.              behavior  of some tr programs, which delete anything
  3591.              they find in  the  SEARCHLIST,  period.)  If  the  s
  3592.              modifier  is specified, sequences of characters that
  3593.              were translated to the same character  are  squashed
  3594.              down to 1 instance of the character.
  3595.  
  3596.              If the d modifier was used, the  REPLACEMENTLIST  is
  3597.              always interpreted exactly as specified.  Otherwise,
  3598.              if the REPLACEMENTLIST is  shorter  than  the  SEAR-
  3599.              CHLIST, the final character is replicated till it is
  3600.              long enough.  If the REPLACEMENTLIST  is  null,  the
  3601.              SEARCHLIST is replicated.  This latter is useful for
  3602.              counting characters in a  class,  or  for  squashing
  3603.              character sequences in a class.
  3604.  
  3605.              Examples:
  3606.  
  3607.                  $ARGV[1] =~ y/A-Z/a-z/;   # canonicalize to lower case
  3608.  
  3609.                  $cnt = tr/*/*/;           # count the stars in $_
  3610.  
  3611.                  $cnt = tr/0-9//;          # count the digits in $_
  3612.  
  3613.                  tr/a-zA-Z//s;             # bookkeeper -> bokeper
  3614.  
  3615.                  ($HOST = $host) =~ tr/a-z/A-Z/;
  3616.  
  3617.                  y/a-zA-Z/ /cs;            # change non-alphas to single space
  3618.  
  3619.                  tr/\200-\377/\0-\177/;    # delete 8th bit
  3620.  
  3621.      truncate(FILEHANDLE,LENGTH)
  3622.      truncate(EXPR,LENGTH)
  3623.              Truncates the file opened on FILEHANDLE, or named by
  3624.              EXPR,  to  the  specified  length.  Produces a fatal
  3625.              error if truncate isn't implemented on your system.
  3626.  
  3627.      umask(EXPR)
  3628.      umask EXPR
  3629.      umask   Sets the umask for the process and returns  the  old
  3630.              one.   If  EXPR  is  omitted, merely returns current
  3631.              umask.
  3632.  
  3633.      undef(EXPR)
  3634.      undef EXPR
  3635.      undef   Undefines the  value  of  EXPR,  which  must  be  an
  3636.              lvalue.   Use  only  on  a  scalar  value, an entire
  3637.              array, or a subroutine name (using &).  (Undef  will
  3638.              probably  not  do what you expect on most predefined
  3639.              variables or dbm array values.) Always  returns  the
  3640.              undefined  value.   You  can omit the EXPR, in which
  3641.              case nothing is undefined,  but  you  still  get  an
  3642.              undefined value that you could, for instance, return
  3643.              from a subroutine.  Examples:
  3644.  
  3645.                   undef $foo;
  3646.                   undef $bar{'blurfl'};
  3647.                   undef @ary;
  3648.                   undef %assoc;
  3649.                   undef &mysub;
  3650.                   return (wantarray ? () : undef) if $they_blew_it;
  3651.  
  3652.      unlink(LIST)
  3653.      unlink LIST
  3654.              Deletes a list of  files.   Returns  the  number  of
  3655.              files successfully deleted.
  3656.  
  3657.                   $cnt = unlink 'a', 'b', 'c';
  3658.                   unlink @goners;
  3659.                   unlink <*.bak>;
  3660.  
  3661.              Note: unlink will not delete directories unless  you
  3662.              are  superuser  and the -U flag is supplied to perl.
  3663.              Even if these conditions are  met,  be  warned  that
  3664.              unlinking  a  directory  can  inflict damage on your
  3665.              filesystem.  Use rmdir instead.
  3666.  
  3667.      unpack(TEMPLATE,EXPR)
  3668.              Unpack does the reverse of pack: it takes  a  string
  3669.              representing  a structure and expands it out into an
  3670.              array value,  returning  the  array  value.   (In  a
  3671.              scalar  context,  it  merely returns the first value
  3672.              produced.) The TEMPLATE has the same  format  as  in
  3673.              the  pack  function.   Here's a subroutine that does
  3674.              substring:
  3675.  
  3676.                   sub substr {
  3677.                        local($what,$where,$howmuch) = @_;
  3678.                        unpack("x$where a$howmuch", $what);
  3679.                   }
  3680.  
  3681.              and then there's
  3682.  
  3683.                   sub ord { unpack("c",$_[0]); }
  3684.  
  3685.              In addition, you may prefix a field with a %<number>
  3686.              to indicate that you want a <number>-bit checksum of
  3687.              the items instead of the items themselves.   Default
  3688.              is  a  16-bit  checksum.  For example, the following
  3689.              computes the same number as the System  V  sum  pro-
  3690.              gram:
  3691.  
  3692.                   while (<>) {
  3693.                       $checksum += unpack("%16C*", $_);
  3694.                   }
  3695.                   $checksum %= 65536;
  3696.  
  3697.      unshift(ARRAY,LIST)
  3698.              Does the opposite of a shift.  Or the opposite of  a
  3699.              push,  depending  on  how  you look at it.  Prepends
  3700.              list to the front of  the  array,  and  returns  the
  3701.              number of elements in the new array.
  3702.  
  3703.                   unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;
  3704.  
  3705.      utime(LIST)
  3706.      utime LIST
  3707.              Changes the access and modification  times  on  each
  3708.              file  of a list of files.  The first two elements of
  3709.              the list must be the NUMERICAL access and  modifica-
  3710.              tion  times,  in  that order.  Returns the number of
  3711.              files successfully changed.  The inode  modification
  3712.              time of each file is set to the current time.  Exam-
  3713.              ple of a "touch" command:
  3714.  
  3715.                   #!/usr/bin/perl
  3716.                   $now = time;
  3717.                   utime $now, $now, @ARGV;
  3718.  
  3719.      values(ASSOC_ARRAY)
  3720.      values ASSOC_ARRAY
  3721.              Returns a normal array consisting of all the  values
  3722.              of  the  named  associative  array.   The values are
  3723.              returned in an apparently random order,  but  it  is
  3724.              the  same order as either the keys() or each() func-
  3725.              tion would produce on  the  same  array.   See  also
  3726.              keys() and each().
  3727.  
  3728.      vec(EXPR,OFFSET,BITS)
  3729.              Treats a string as a vector  of  unsigned  integers,
  3730.              and  returns  the  value  of the bitfield specified.
  3731.              May also be assigned to.  BITS must be  a  power  of
  3732.              two from 1 to 32.
  3733.  
  3734.              Vectors created with vec() can also  be  manipulated
  3735.              with  the  logical  operators |, & and ^, which will
  3736.              assume a bit vector operation is desired  when  both
  3737.              operands  are  strings.   This interpretation is not
  3738.              enabled unless there is at least one vec()  in  your
  3739.              program, to protect older programs.
  3740.  
  3741.              To transform a bit vector into a string or array  of
  3742.              0's and 1's, use these:
  3743.  
  3744.                   $bits = unpack("b*", $vector);
  3745.                   @bits = split(//, unpack("b*", $vector));
  3746.  
  3747.              If you know the exact length in bits, it can be used
  3748.              in place of the *.
  3749.  
  3750.      wait    Waits for a child process to terminate  and  returns
  3751.              the  pid of the deceased process, or -1 if there are
  3752.              no child processes.  The status is returned in $?.
  3753.  
  3754.      waitpid(PID,FLAGS)
  3755.              Waits for a particular child  process  to  terminate
  3756.              and  returns  the pid of the deceased process, or -1
  3757.              if there is no such child process.   The  status  is
  3758.              returned in $?.  If you say
  3759.  
  3760.                   require "sys/wait.h";
  3761.                   ...
  3762.                   waitpid(-1,&WNOHANG);
  3763.  
  3764.              then you can do a non-blocking wait for any process.
  3765.  
  3766.              Non-blocking wait is only available on machines sup-
  3767.              porting either the waitpid (2) or wait4  (2)  system
  3768.              calls.   However,  waiting for a particular pid with
  3769.              FLAGS of 0 is implemented  everywhere.   (Perl  emu-
  3770.              lates  the  system  call  by  remembering the status
  3771.              values of processes that have exited  but  have  not
  3772.              been harvested by the Perl script yet.)
  3773.  
  3774.      wantarray
  3775.              Returns true if the context of the currently execut-
  3776.              ing  subroutine  is  looking  for  an  array  value.
  3777.              Returns false  if  the  context  is  looking  for  a
  3778.              scalar.
  3779.  
  3780.                   return wantarray ? () : undef;
  3781.  
  3782.      warn(LIST)
  3783.      warn LIST
  3784.              Produces a message on STDERR just  like  "die",  but
  3785.              doesn't exit.
  3786.  
  3787.      write(FILEHANDLE)
  3788.      write(EXPR)
  3789.      write   Writes a formatted record (possibly  multi-line)  to
  3790.              the specified file, using the format associated with
  3791.              that file.  By default the format for a file is  the
  3792.              one  having the same name is the filehandle, but the
  3793.              format for the current output channel  (see  select)
  3794.              may  be  set explicitly by assigning the name of the
  3795.              format to the $~ variable.
  3796.  
  3797.              Top of form processing is handled automatically:  if
  3798.              there  is  insufficient room on the current page for
  3799.              the formatted record, the page is advanced by  writ-
  3800.              ing  a  form  feed,  a special top-of-page format is
  3801.              used to format the new page  header,  and  then  the
  3802.              record  is written.  By default the top-of-page for-
  3803.              mat is  the  name  of  the  filehandle  with  "_TOP"
  3804.              appended, but it may be dynamicallly set to the for-
  3805.              mat of your choice by assigning the name to  the  $^
  3806.              variable  while  the  filehandle  is  selected.  The
  3807.              number of lines remaining on the current page is  in
  3808.              variable  $-,  which  can be set to 0 to force a new
  3809.              page.
  3810.  
  3811.              If FILEHANDLE is unspecified,  output  goes  to  the
  3812.              current  default output channel, which starts out as
  3813.              STDOUT but may be changed by  the  select  operator.
  3814.  
  3815.              If the FILEHANDLE is an EXPR, then the expression is
  3816.              evaluated and the resulting string is used  to  look
  3817.              up the name of the FILEHANDLE at run time.  For more
  3818.              on formats, see the section on Formats later on.
  3819.  
  3820.              Note that write is NOT the opposite of read.
  3821.  
  3822. ==
  3823.      Precedence
  3824.  
  3825.      Perl operators have the  following  associativity  and  pre-
  3826.      cedence:
  3827.  
  3828.      nonassoc  print printf exec system sort reverse
  3829.                     chmod chown kill unlink utime die return
  3830.      left      ,
  3831.      right     = += -= *= etc.
  3832.      right     ?:
  3833.      nonassoc  ..
  3834.      left      ||
  3835.      left      &&
  3836.      left      | ^
  3837.      left      &
  3838.      nonassoc  == != <=> eq ne cmp
  3839.      nonassoc  < > <= >= lt gt le ge
  3840.      nonassoc  chdir exit eval reset sleep rand umask
  3841.      nonassoc  -r -w -x etc.
  3842.      left      << >>
  3843.      left      + - .
  3844.      left      * / % x
  3845.      left      =~ !~
  3846.      right     ! ~ and unary minus
  3847.      right     **
  3848.      nonassoc  ++ --
  3849.      left      '('
  3850.  
  3851.      As mentioned earlier, if any list operator (print, etc.)  or
  3852.      any  unary  operator  (chdir,  etc.)  is  followed by a left
  3853.      parenthesis as the next token on the same line, the operator
  3854.      and  arguments within parentheses are taken to be of highest
  3855.      precedence, just like a normal function call.  Examples:
  3856.  
  3857.           chdir $foo || die;       # (chdir $foo) || die
  3858.           chdir($foo) || die;      # (chdir $foo) || die
  3859.           chdir ($foo) || die;     # (chdir $foo) || die
  3860.           chdir +($foo) || die;    # (chdir $foo) || die
  3861.  
  3862.      but, because * is higher precedence than ||:
  3863.  
  3864.           chdir $foo * 20;         # chdir ($foo * 20)
  3865.           chdir($foo) * 20;        # (chdir $foo) * 20
  3866.           chdir ($foo) * 20;       # (chdir $foo) * 20
  3867.           chdir +($foo) * 20;      # chdir ($foo * 20)
  3868.  
  3869.           rand 10 * 20;            # rand (10 * 20)
  3870.           rand(10) * 20;           # (rand 10) * 20
  3871.           rand (10) * 20;          # (rand 10) * 20
  3872.           rand +(10) * 20;         # rand (10 * 20)
  3873.  
  3874.      In the absence of parentheses, the precedence of list opera-
  3875.      tors  such  as  print,  sort or chmod is either very high or
  3876.      very low depending on whether you look at the left  side  of
  3877.      operator or the right side of it.  For example, in
  3878.  
  3879.           @ary = (1, 3, sort 4, 2);
  3880.           print @ary;         # prints 1324
  3881.  
  3882.      the commas on the right of the sort are evaluated before the
  3883.      sort,  but  the  commas on the left are evaluated after.  In
  3884.      other words, list operators tend to gobble up all the  argu-
  3885.      ments that follow them, and then act like a simple term with
  3886.      regard to the preceding expression.  Note that you  have  to
  3887.      be careful with parens:
  3888.  
  3889.           # These evaluate exit before doing the print:
  3890.           print($foo, exit);  # Obviously not what you want.
  3891.           print $foo, exit;   # Nor is this.
  3892.  
  3893.           # These do the print before evaluating exit:
  3894.           (print $foo), exit; # This is what you want.
  3895.           print($foo), exit;  # Or this.
  3896.           print ($foo), exit; # Or even this.
  3897.  
  3898.      Also note that
  3899.  
  3900.           print ($foo & 255) + 1, "\n";
  3901.  
  3902.      probably doesn't do what you expect at first glance.
  3903.  
  3904.      Subroutines
  3905.  
  3906.      A subroutine may be declared as follows:
  3907.  
  3908.          sub NAME BLOCK
  3909.  
  3910.      Any arguments passed to the routine come  in  as  array  @_,
  3911.      that is ($_[0], $_[1], ...).  The array @_ is a local array,
  3912.      but its values are references to the actual  scalar  parame-
  3913.      ters.   The  return  value of the subroutine is the value of
  3914.      the last expression evaluated, and can be  either  an  array
  3915.      value  or  a  scalar value.  Alternately, a return statement
  3916.      may be used to specify the returned value and exit the  sub-
  3917.      routine.  To create local variables see the local operator.
  3918.  
  3919.      A subroutine is called using the do operator or the & opera-
  3920.      tor.
  3921.  
  3922.      Example:
  3923.  
  3924.           sub MAX {
  3925.                local($max) = pop(@_);
  3926.                foreach $foo (@_) {
  3927.                     $max = $foo if $max < $foo;
  3928.                }
  3929.                $max;
  3930.           }
  3931.  
  3932.           ...
  3933.           $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  3934.  
  3935.      Example:
  3936.  
  3937.           # get a line, combining continuation lines
  3938.           #  that start with whitespace
  3939.           sub get_line {
  3940.                $thisline = $lookahead;
  3941.                line: while ($lookahead = <STDIN>) {
  3942.                     if ($lookahead =~ /^[ \t]/) {
  3943.                          $thisline .= $lookahead;
  3944.                     }
  3945.                     else {
  3946.                          last line;
  3947.                     }
  3948.                }
  3949.                $thisline;
  3950.           }
  3951.  
  3952.           $lookahead = <STDIN>;    # get first line
  3953.           while ($_ = do get_line()) {
  3954.                ...
  3955.           }
  3956.  
  3957.      Use array assignment to a local list to name your formal arguments:
  3958.  
  3959.           sub maybeset {
  3960.                local($key, $value) = @_;
  3961.                $foo{$key} = $value unless $foo{$key};
  3962.           }
  3963.  
  3964.      This also has the effect of turning  call-by-reference  into
  3965.      call-by-value, since the assignment copies the values.
  3966.  
  3967.      Subroutines may be called recursively.  If a  subroutine  is
  3968.      called  using the & form, the argument list is optional.  If
  3969.      omitted, no @_ array is set up for the  subroutine;  the  @_
  3970.      array  at  the  time  of  the  call is visible to subroutine
  3971.      instead.
  3972.  
  3973.           do foo(1,2,3);      # pass three arguments
  3974.           &foo(1,2,3);        # the same
  3975.  
  3976.           do foo();      # pass a null list
  3977.           &foo();             # the same
  3978.           &foo;               # pass no arguments--more efficient
  3979.  
  3980.      Passing By Reference
  3981.  
  3982.      Sometimes you don't want to pass the value of an array to  a
  3983.      subroutine but rather the name of it, so that the subroutine
  3984.      can modify the global copy of it rather than working with  a
  3985.      local  copy.   In perl you can refer to all the objects of a
  3986.      particular name by prefixing the name  with  a  star:  *foo.
  3987.      When  evaluated,  it produces a scalar value that represents
  3988.      all the objects of that name, including any filehandle, for-
  3989.      mat or subroutine.  When assigned to within a local() opera-
  3990.      tion, it causes the name mentioned to refer  to  whatever  *
  3991.      value was assigned to it.  Example:
  3992.  
  3993.           sub doubleary {
  3994.               local(*someary) = @_;
  3995.               foreach $elem (@someary) {
  3996.                $elem *= 2;
  3997.               }
  3998.           }
  3999.           do doubleary(*foo);
  4000.           do doubleary(*bar);
  4001.  
  4002.      Assignment to *name is currently recommended only  inside  a
  4003.      local().  You can actually assign to *name anywhere, but the
  4004.      previous referent of *name may be  stranded  forever.   This
  4005.      may or may not bother you.
  4006.  
  4007.      Note that scalars are already passed by  reference,  so  you
  4008.      can  modify scalar arguments without using this mechanism by
  4009.      referring explicitly to the $_[nnn] in  question.   You  can
  4010.      modify  all the elements of an array by passing all the ele-
  4011.      ments as scalars, but you have to use  the  *  mechanism  to
  4012.      push,  pop  or change the size of an array.  The * mechanism
  4013.      will probably be more efficient in any case.
  4014.  
  4015.      Since a *name value contains unprintable binary data, if  it
  4016.      is  used as an argument in a print, or as a %s argument in a
  4017.      printf or sprintf, it then has the value '*name', just so it
  4018.      prints out pretty.
  4019.  
  4020.      Even if you don't want to modify an array, this mechanism is
  4021.      useful  for  passing multiple arrays in a single LIST, since
  4022.      normally the LIST mechanism will merge all the array  values
  4023.      so that you can't extract out the individual arrays.
  4024.  
  4025.      Regular Expressions
  4026.  
  4027.      The patterns used in pattern matching  are  regular  expres-
  4028.      sions  such  as  those supplied in the Version 8 regexp rou-
  4029.      tines.  (In  fact,  the  routines  are  derived  from  Henry
  4030.      Spencer's  freely redistributable reimplementation of the V8
  4031.      routines.) In addition, \w matches an alphanumeric character
  4032.      (including  "_")  and \W a nonalphanumeric.  Word boundaries
  4033.      may be matched by \b, and  non-boundaries  by  \B.   A  whi-
  4034.      tespace character is matched by \s, non-whitespace by \S.  A
  4035.      numeric character is matched by \d, non-numeric by \D.   You
  4036.      may  use  \w, \s and \d within character classes.  Also, \n,
  4037.      \r, \f, \t  and  \NNN  have  their  normal  interpretations.
  4038.      Within character classes \b represents backspace rather than
  4039.      a word boundary.  Alternatives may be separated by  |.   The
  4040.      bracketing construct ( ... ) may also be used, in which case
  4041.      \<digit> matches the digit'th substring.   (Outside  of  the
  4042.      pattern,  always  use  $ instead of \ in front of the digit.
  4043.      The scope of $<digit> (and $`, $& and $') extends to the end
  4044.      of  the  enclosing BLOCK or eval string, or to the next pat-
  4045.      tern match with subexpressions.  The \<digit> notation some-
  4046.      times  works  outside the current pattern, but should not be
  4047.      relied upon.) You may have as many parentheses as you  wish.
  4048.      If  you have more than 9 substrings, the variables $10, $11,
  4049.      ... refer to the corresponding substring.  Within  the  pat-
  4050.      tern,  \10, \11, etc. refer back to substrings if there have
  4051.      been at least that many left parens  before  the  backrefer-
  4052.      ence.  Otherwise (for backward compatibilty) \10 is the same
  4053.      as \010, a backspace, and \11 the same as \011, a tab.   And
  4054.      so on.  (\1 through \9 are always backreferences.)
  4055.  
  4056.      $+ returns whatever the  last  bracket  match  matched.   $&
  4057.      returns  the  entire matched string.  ($0 used to return the
  4058.      same thing, but not any more.) $` returns everything  before
  4059.      the matched string.  $' returns everything after the matched
  4060.      string.  Examples:
  4061.  
  4062.           s/^([^ ]*) *([^ ]*)/$2 $1/;   # swap first two words
  4063.  
  4064.           if (/Time: (..):(..):(..)/) {
  4065.                $hours = $1;
  4066.                $minutes = $2;
  4067.                $seconds = $3;
  4068.           }
  4069.  
  4070.      By default, the ^ character is only guaranteed to  match  at
  4071.      the beginning of the string, the $ character only at the end
  4072.      (or before the newline at the end)  and  perl  does  certain
  4073.      optimizations  with  the assumption that the string contains
  4074.      only one line.  The behavior of ^ and $ on embedded newlines
  4075.      will  be  inconsistent.   You  may, however, wish to treat a
  4076.      string as a multi-line buffer, such that the  ^  will  match
  4077.      after any newline within the string, and $ will match before
  4078.      any newline.  At the cost of a little more overhead, you can
  4079.      do this by setting the variable $* to 1.  Setting it back to
  4080.      0 makes perl revert to its old behavior.
  4081.  
  4082.      To facilitate  multi-line  substitutions,  the  .  character
  4083.      never matches a newline (even when $* is 0).  In particular,
  4084.      the following leaves a newline on the $_ string:
  4085.  
  4086.           $_ = <STDIN>;
  4087.           s/.*(some_string).*/$1/;
  4088.  
  4089.      If the newline is unwanted, try one of
  4090.  
  4091.           s/.*(some_string).*\n/$1/;
  4092.           s/.*(some_string)[^\000]*/$1/;
  4093.           s/.*(some_string)(.|\n)*/$1/;
  4094.           chop; s/.*(some_string).*/$1/;
  4095.           /(some_string)/ && ($_ = $1);
  4096.  
  4097.      Any item of a regular expression may be followed with digits
  4098.      in  curly  brackets  of  the  form  {n,m}, where n gives the
  4099.      minimum number of times to match the item and  m  gives  the
  4100.      maximum.   The  form  {n} is equivalent to {n,n} and matches
  4101.      exactly n times.  The form {n,} matches  n  or  more  times.
  4102.      (If  a  curly  bracket  occurs  in  any other context, it is
  4103.      treated  as  a  regular  character.)  The  *   modifier   is
  4104.      equivalent  to {0,}, the + modifier to {1,} and the ? modif-
  4105.      ier to {0,1}.  There is no limit to the size of n or m,  but
  4106.      large numbers will chew up more memory.
  4107.  
  4108.      You will note that all backslashed  metacharacters  in  perl
  4109.      are  alphanumeric,  such  as  \b, \w, \n.  Unlike some other
  4110.      regular expression languages, there are no backslashed  sym-
  4111.      bols  that aren't alphanumeric.  So anything that looks like
  4112.      \\, \(, \), \<, \>, \{, or \} is  always  interpreted  as  a
  4113.      literal  character, not a metacharacter.  This makes it sim-
  4114.      ple to quote a string that you want to use for a pattern but
  4115.      that  you  are  afraid might contain metacharacters.  Simply
  4116.      quote all the non-alphanumeric characters:
  4117.  
  4118.           $pattern =~ s/(\W)/\\$1/g;
  4119.  
  4120.      Formats
  4121.  
  4122.      Output record formats for use with the  write  operator  may
  4123.      declared as follows:
  4124.  
  4125.          format NAME =
  4126.          FORMLIST
  4127.          .
  4128.  
  4129.      If name is omitted, format "STDOUT"  is  defined.   FORMLIST
  4130.      consists of a sequence of lines, each of which may be of one
  4131.      of three types:
  4132.  
  4133.      1.  A comment.
  4134.  
  4135.      2.  A "picture" line giving the format for one output line.
  4136.  
  4137.      3.  An argument line supplying values to plug into a picture
  4138.          line.
  4139.  
  4140.      Picture lines are printed exactly as they look,  except  for
  4141.      certain  fields  that substitute values into the line.  Each
  4142.      picture field starts with either @ or ^.  The @  field  (not
  4143.      to  be confused with the array marker @) is the normal case;
  4144.      ^ fields are used to do rudimentary  multi-line  text  block
  4145.      filling.  The length of the field is supplied by padding out
  4146.      the field with multiple <, >, or |  characters  to  specify,
  4147.      respectively,  left  justification,  right justification, or
  4148.      centering.  As an alternate form of right justification, you
  4149.      may  also use # characters (with an optional .) to specify a
  4150.      numeric field.  (Use of ^ instead of @ causes the  field  to
  4151.      be  blanked if undefined.) If any of the values supplied for
  4152.      these fields contains a newline, only the  text  up  to  the
  4153.      newline  is  printed.   The special field @* can be used for
  4154.      printing multi-line values.  It should appear by itself on a
  4155.      line.
  4156.  
  4157.      The values are specified on the following line, in the  same
  4158.      order as the picture fields.  The values should be separated
  4159.      by commas.
  4160.  
  4161.      Picture fields that begin with ^ rather than @  are  treated
  4162.      specially.   The  value  supplied  must be a scalar variable
  4163.      name which contains a text string.  Perl puts as  much  text
  4164.      as  it  can  into the field, and then chops off the front of
  4165.      the string so that the next time the variable is referenced,
  4166.      more  of  the text can be printed.  Normally you would use a
  4167.      sequence of fields in a vertical stack to print out a  block
  4168.      of text.  If you like, you can end the final field with ...,
  4169.      which will appear in the output if the text was too long  to
  4170.      appear in its entirety.  You can change which characters are
  4171.      legal to break on by changing the variable $: to a  list  of
  4172.      the desired characters.
  4173.  
  4174.      Since use of ^ fields can produce variable length records if
  4175.      the  text  to  be formatted is short, you can suppress blank
  4176.      lines by putting the tilde (~)  character  anywhere  in  the
  4177.      line.  (Normally you should put it in the front if possible,
  4178.      for visibility.) The tilde will be  translated  to  a  space
  4179.      upon  output.   If  you put a second tilde contiguous to the
  4180.      first, the line will be repeated until all the fields on the
  4181.      line  are  exhausted.  (If you use a field of the @ variety,
  4182.      the expression you supply had better not give the same value
  4183.      every time forever!)
  4184.  
  4185.      Examples:
  4186.  
  4187.      # a report on the /etc/passwd file
  4188.      format STDOUT_TOP =
  4189.                              Passwd File
  4190.      Name                Login    Office   Uid   Gid Home
  4191.      ------------------------------------------------------------------
  4192.      .
  4193.      format STDOUT =
  4194.      @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  4195.      $name,              $login,  $office,$uid,$gid, $home
  4196.      .
  4197.  
  4198.      # a report from a bug report form
  4199.      format STDOUT_TOP =
  4200.                              Bug Reports
  4201.      @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  4202.      $system,                      $%,         $date
  4203.      ------------------------------------------------------------------
  4204.      .
  4205.      format STDOUT =
  4206.      Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4207.               $subject
  4208.      Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4209.             $index,                       $description
  4210.      Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4211.                $priority,        $date,   $description
  4212.      From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4213.            $from,                         $description
  4214.      Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4215.                   $programmer,            $description
  4216.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4217.                                           $description
  4218.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4219.                                           $description
  4220.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4221.                                           $description
  4222.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4223.                                           $description
  4224.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  4225.                                           $description
  4226.      .
  4227.  
  4228.      It is possible to intermix prints with writes  on  the  same
  4229.      output  channel, but you'll have to handle $- (lines left on
  4230.      the page) yourself.
  4231.  
  4232.      If you are printing lots of fields that are  usually  blank,
  4233.      you   should  consider  using  the  reset  operator  between
  4234.      records.  Not only is it more efficient, but it can  prevent
  4235.      the bug of adding another field and forgetting to zero it.
  4236.  
  4237.      Interprocess Communication
  4238.  
  4239.      The IPC facilities of perl are built on the Berkeley  socket
  4240.      mechanism.   If  you don't have sockets, you can ignore this
  4241.      section.  The calls have the same names as the corresponding
  4242.      system calls, but the arguments tend to differ, for two rea-
  4243.      sons.  First, perl file handles work differently than C file
  4244.      descriptors.   Second,  perl already knows the length of its
  4245.      strings, so you don't need to pass that  information.   Here
  4246.      is a sample client (untested):
  4247.  
  4248.           ($them,$port) = @ARGV;
  4249.           $port = 2345 unless $port;
  4250.           $them = 'localhost' unless $them;
  4251.  
  4252.           $SIG{'INT'} = 'dokill';
  4253.           sub dokill { kill 9,$child if $child; }
  4254.  
  4255.           require 'sys/socket.ph';
  4256.  
  4257.           $sockaddr = 'S n a4 x8';
  4258.           chop($hostname = `hostname`);
  4259.  
  4260.           ($name, $aliases, $proto) = getprotobyname('tcp');
  4261.           ($name, $aliases, $port) = getservbyname($port, 'tcp')
  4262.                unless $port =~ /^\d+$/;
  4263.           ($name, $aliases, $type, $len, $thisaddr) =
  4264.                               gethostbyname($hostname);
  4265.           ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
  4266.  
  4267.           $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
  4268.           $that = pack($sockaddr, &AF_INET, $port, $thataddr);
  4269.  
  4270.           socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  4271.           bind(S, $this) || die "bind: $!";
  4272.           connect(S, $that) || die "connect: $!";
  4273.  
  4274.           select(S); $| = 1; select(stdout);
  4275.  
  4276.           if ($child = fork) {
  4277.                while (<>) {
  4278.                     print S;
  4279.                }
  4280.                sleep 3;
  4281.  
  4282.                do dokill();
  4283.           }
  4284.           else {
  4285.                while (<S>) {
  4286.                     print;
  4287.                }
  4288.           }
  4289.  
  4290.      And here's a server:
  4291.  
  4292.           ($port) = @ARGV;
  4293.           $port = 2345 unless $port;
  4294.  
  4295.           require 'sys/socket.ph';
  4296.  
  4297.           $sockaddr = 'S n a4 x8';
  4298.  
  4299.           ($name, $aliases, $proto) = getprotobyname('tcp');
  4300.           ($name, $aliases, $port) = getservbyname($port, 'tcp')
  4301.                unless $port =~ /^\d+$/;
  4302.  
  4303.           $this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");
  4304.  
  4305.           select(NS); $| = 1; select(stdout);
  4306.  
  4307.           socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  4308.           bind(S, $this) || die "bind: $!";
  4309.           listen(S, 5) || die "connect: $!";
  4310.  
  4311.           select(S); $| = 1; select(stdout);
  4312.  
  4313.           for (;;) {
  4314.                print "Listening again\n";
  4315.                ($addr = accept(NS,S)) || die $!;
  4316.                print "accept ok\n";
  4317.  
  4318.                ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
  4319.                @inetaddr = unpack('C4',$inetaddr);
  4320.                print "$af $port @inetaddr\n";
  4321.  
  4322.                while (<NS>) {
  4323.                     print;
  4324.                     print NS;
  4325.                }
  4326.           }
  4327.  
  4328.      Predefined Names
  4329.  
  4330.      The following names have special meaning to perl.   I  could
  4331.      have used alphabetic symbols for some of these, but I didn't
  4332.      want to  take  the  chance  that  someone  would  say  reset
  4333.      "a-zA-Z"  and wipe them all out.  You'll just have to suffer
  4334.      along with these silly symbols.  Most of them  have  reason-
  4335.      able mnemonics, or analogues in one of the shells.
  4336.  
  4337.      $_      The default input and pattern-searching space.   The
  4338.              following pairs are equivalent:
  4339.  
  4340.                   while (<>) {...     # only equivalent in while!
  4341.                   while ($_ = <>) {...
  4342.  
  4343.                   /^Subject:/
  4344.                   $_ =~ /^Subject:/
  4345.  
  4346.                   y/a-z/A-Z/
  4347.                   $_ =~ y/a-z/A-Z/
  4348.  
  4349.                   chop
  4350.                   chop($_)
  4351.  
  4352.              (Mnemonic: underline is understood in certain opera-
  4353.              tions.)
  4354.  
  4355.      $.      The current input line number of the last filehandle
  4356.              that  was  read.   Readonly.   Remember that only an
  4357.              explicit close on the  filehandle  resets  the  line
  4358.              number.  Since <> never does an explicit close, line
  4359.              numbers increase across ARGV files (but see examples
  4360.              under  eof).  (Mnemonic: many programs use . to mean
  4361.              the current line number.)
  4362.  
  4363.      $/      The input  record  separator,  newline  by  default.
  4364.              Works  like  awk's  RS  variable, including treating
  4365.              blank lines as delimiters if set to the null string.
  4366.              You may set it to a multicharacter string to match a
  4367.              multi-character delimiter.  (Mnemonic: / is used  to
  4368.              delimit line boundaries when quoting poetry.)
  4369.  
  4370.      $,      The output field separator for the  print  operator.
  4371.              Ordinarily  the print operator simply prints out the
  4372.              comma separated fields you specify.  In order to get
  4373.              behavior  more  like  awk,  set this variable as you
  4374.              would set awk's OFS  variable  to  specify  what  is
  4375.              printed  between fields.  (Mnemonic: what is printed
  4376.              when there is a , in your print statement.)
  4377.  
  4378.      $"      This is like $, except  that  it  applies  to  array
  4379.              values  interpolated into a double-quoted string (or
  4380.              similar interpreted string).  Default  is  a  space.
  4381.              (Mnemonic: obvious, I think.)
  4382.  
  4383.      $\      The output record separator for the print  operator.
  4384.              Ordinarily  the print operator simply prints out the
  4385.              comma separated fields you specify, with no trailing
  4386.              newline  or  record  separator assumed.  In order to
  4387.              get behavior more like awk, set this variable as you
  4388.              would  set  awk's  ORS  variable  to specify what is
  4389.              printed at the end of the print.  (Mnemonic: you set
  4390.              $\  instead  of  adding  \n at the end of the print.
  4391.              Also, it's just like /, but it's what you get "back"
  4392.              from perl.)
  4393.  
  4394.      $#      The output format for printed numbers.   This  vari-
  4395.              able is a half-hearted attempt to emulate awk's OFMT
  4396.              variable.  There are times, however,  when  awk  and
  4397.              perl  have  differing  notions  of  what  is in fact
  4398.              numeric.  Also, the initial value  is  %.20g  rather
  4399.              than  %.6g,  so you need to set $# explicitly to get
  4400.              awk's value.  (Mnemonic: # is the number sign.)
  4401.  
  4402.      $%      The current page number of  the  currently  selected
  4403.              output  channel.   (Mnemonic:  %  is  page number in
  4404.              nroff.)
  4405.  
  4406.      $=      The current page length  (printable  lines)  of  the
  4407.              currently  selected  output channel.  Default is 60.
  4408.              (Mnemonic: = has horizontal lines.)
  4409.  
  4410.      $-      The  number  of  lines  left  on  the  page  of  the
  4411.              currently   selected   output  channel.   (Mnemonic:
  4412.              lines_on_page - lines_printed.)
  4413.  
  4414.      $~      The name  of  the  current  report  format  for  the
  4415.              currently  selected output channel.  Default is name
  4416.              of the filehandle.  (Mnemonic: brother to $^.)
  4417.  
  4418.      $^      The name of the current top-of-page format  for  the
  4419.              currently  selected output channel.  Default is name
  4420.              of the filehandle with "_TOP" appended.   (Mnemonic:
  4421.              points to top of page.)
  4422.  
  4423.      $|      If set to nonzero, forces a flush after every  write
  4424.              or  print  on the currently selected output channel.
  4425.              Default is 0.  Note that STDOUT  will  typically  be
  4426.              line buffered if output is to the terminal and block
  4427.              buffered otherwise.  Setting this variable is useful
  4428.              primarily when you are outputting to a pipe, such as
  4429.              when you are running a perl  script  under  rsh  and
  4430.              want   to   see   the   output  as  it's  happening.
  4431.              (Mnemonic: when you want your  pipes  to  be  piping
  4432.              hot.)
  4433.  
  4434.      $$      The process number of the perl running this  script.
  4435.              (Mnemonic: same as shells.)
  4436.  
  4437.      $?      The status returned by the last pipe close, backtick
  4438.              (``)  command or system operator.  Note that this is
  4439.              the status word returned by the wait() system  call,
  4440.              so  the exit value of the subprocess is actually ($?
  4441.              >> 8).  $? & 255 gives which  signal,  if  any,  the
  4442.              process  died  from,  and  whether  there was a core
  4443.              dump.  (Mnemonic: similar to sh and ksh.)
  4444.  
  4445.      $&      The string matched by the last  pattern  match  (not
  4446.              counting  any  matches hidden within a BLOCK or eval
  4447.              enclosed by the current BLOCK).  (Mnemonic:  like  &
  4448.              in some editors.)
  4449.  
  4450.      $`      The string preceding whatever  was  matched  by  the
  4451.              last  pattern match (not counting any matches hidden
  4452.              within a BLOCK  or  eval  enclosed  by  the  current
  4453.              BLOCK).    (Mnemonic:  `  often  precedes  a  quoted
  4454.              string.)
  4455.  
  4456.      $'      The string following whatever  was  matched  by  the
  4457.              last  pattern match (not counting any matches hidden
  4458.              within a BLOCK  or  eval  enclosed  by  the  current
  4459.              BLOCK).    (Mnemonic:   '  often  follows  a  quoted
  4460.              string.) Example:
  4461.  
  4462.                   $_ = 'abcdefghi';
  4463.                   /def/;
  4464.                   print "$`:$&:$'\n";      # prints abc:def:ghi
  4465.  
  4466.      $+      The last bracket matched by the last search pattern.
  4467.              This  is  useful if you don't know which of a set of
  4468.              alternative patterns matched.  For example:
  4469.  
  4470.                  /Version: (.*)|Revision: (.*)/ && ($rev = $+);
  4471.  
  4472.              (Mnemonic: be positive and forward looking.)
  4473.  
  4474.      $*      Set to 1 to do multiline matching within a string, 0
  4475.              to tell perl that it can assume that strings contain
  4476.              a single line, for the purpose of optimizing pattern
  4477.              matches.  Pattern matches on strings containing mul-
  4478.              tiple newlines can produce confusing results when $*
  4479.              is  0.  Default is 0.  (Mnemonic: * matches multiple
  4480.              things.) Note that this variable only influences the
  4481.              interpretation of ^ and $.  A literal newline can be
  4482.              searched for even when $* == 0.
  4483.  
  4484.      $0      Contains the name of the file  containing  the  perl
  4485.              script being executed.  Assigning to $0 modifies the
  4486.              argument  area  that   the   ps(1)   program   sees.
  4487.              (Mnemonic: same as sh and ksh.)
  4488.  
  4489.      $<digit>
  4490.              Contains the subpattern from the  corresponding  set
  4491.              of  parentheses  in  the  last  pattern matched, not
  4492.              counting patterns matched in nested blocks that have
  4493.              been exited already.  (Mnemonic: like \digit.)
  4494.  
  4495.      $[      The index of the first element in an array,  and  of
  4496.              the  first  character in a substring.  Default is 0,
  4497.              but you could set it to 1 to make perl  behave  more
  4498.              like  awk  (or  Fortran)  when subscripting and when
  4499.              evaluating  the  index()  and  substr()   functions.
  4500.              (Mnemonic: [ begins subscripts.)
  4501.  
  4502.      $]      The string printed out when you say "perl  -v".   It
  4503.              can  be  used  to  determine  at  the beginning of a
  4504.              script whether the perl  interpreter  executing  the
  4505.              script  is  in the right range of versions.  If used
  4506.              in  a  numeric  context,  returns  the   version   +
  4507.              patchlevel / 1000.  Example:
  4508.  
  4509.                   # see if getc is available
  4510.                      ($version,$patchlevel) =
  4511.                         $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
  4512.                      print STDERR "(No filename completion available.)\n"
  4513.                         if $version * 1000 + $patchlevel < 2016;
  4514.  
  4515.              or, used numerically,
  4516.  
  4517.                   warn "No checksumming!\n" if $] < 3.019;
  4518.  
  4519.              (Mnemonic: Is this version  of  perl  in  the  right
  4520.              bracket?)
  4521.  
  4522.      $;      The subscript separator for multi-dimensional  array
  4523.              emulation.   If  you  refer  to an associative array
  4524.              element as
  4525.                   $foo{$a,$b,$c}
  4526.  
  4527.              it really means
  4528.  
  4529.                   $foo{join($;, $a, $b, $c)}
  4530.  
  4531.              But don't put
  4532.  
  4533.                   @foo{$a,$b,$c}      # a slice--note the @
  4534.  
  4535.              which means
  4536.  
  4537.                   ($foo{$a},$foo{$b},$foo{$c})
  4538.  
  4539.              Default is "\034", the same as SUBSEP in awk.   Note
  4540.              that  if  your  keys contain binary data there might
  4541.              not be any safe value for $;.  (Mnemonic: comma (the
  4542.              syntactic  subscript separator) is a semi-semicolon.
  4543.              Yeah, I know, it's pretty lame, but  $,  is  already
  4544.              taken for something more important.)
  4545.  
  4546.      $!      If used in a numeric  context,  yields  the  current
  4547.              value  of  errno, with all the usual caveats.  (This
  4548.              means that you shouldn't depend on the value  of  $!
  4549.              to  be anything in particular unless you've gotten a
  4550.              specific error return indicating a system error.) If
  4551.              used  in  a string context, yields the corresponding
  4552.              system error string.  You can assign to $! in  order
  4553.              to set errno if, for instance, you want $! to return
  4554.              the string for error n, or you want to set the  exit
  4555.              value  for  the  die operator.  (Mnemonic: What just
  4556.              went bang?)
  4557.  
  4558.      $@      The perl syntax error message  from  the  last  eval
  4559.              command.  If null, the last eval parsed and executed
  4560.              correctly (although the operations you  invoked  may
  4561.              have  failed  in  the  normal  fashion).  (Mnemonic:
  4562.              Where was the syntax error "at"?)
  4563.  
  4564.      $<      The real uid of this process.  (Mnemonic:  it's  the
  4565.              uid you came FROM, if you're running setuid.)
  4566.  
  4567.      $>      The effective uid of this process.  Example:
  4568.  
  4569.                   $< = $>;  # set real uid to the effective uid
  4570.                   ($<,$>) = ($>,$<);  # swap real and effective uid
  4571.  
  4572.              (Mnemonic: it's the uid you went TO, if you're  run-
  4573.              ning setuid.) Note: $< and $> can only be swapped on
  4574.              machines supporting setreuid().
  4575.  
  4576.      $(      The real gid of this  process.   If  you  are  on  a
  4577.              machine  that supports membership in multiple groups
  4578.              simultaneously, gives  a  space  separated  list  of
  4579.              groups  you  are  in.   The  first number is the one
  4580.              returned by getgid(), and  the  subsequent  ones  by
  4581.              getgroups(),  one  of  which  may be the same as the
  4582.              first number.  (Mnemonic: parentheses  are  used  to
  4583.              GROUP  things.   The real gid is the group you LEFT,
  4584.              if you're running setgid.)
  4585.  
  4586.      $)      The effective gid of this process.  If you are on  a
  4587.              machine  that supports membership in multiple groups
  4588.              simultaneously, gives  a  space  separated  list  of
  4589.              groups  you  are  in.   The  first number is the one
  4590.              returned by getegid(), and the  subsequent  ones  by
  4591.              getgroups(),  one  of  which  may be the same as the
  4592.              first number.  (Mnemonic: parentheses  are  used  to
  4593.              GROUP things.  The effective gid is the group that's
  4594.              RIGHT for you, if you're running setgid.)
  4595.  
  4596.              Note: $<, $>, $( and $) can only be set on  machines
  4597.              that  support the corresponding set[re][ug]id() rou-
  4598.              tine.  $( and $) can only  be  swapped  on  machines
  4599.              supporting setregid().
  4600.  
  4601.      $:      The current set of characters after which  a  string
  4602.              may  be broken to fill continuation fields (starting
  4603.              with ^) in a format.  Default is " \n-", to break on
  4604.              whitespace or hyphens.  (Mnemonic: a "colon" in poe-
  4605.              try is a part of a line.)
  4606.  
  4607.      $^D     The  current   value   of   the   debugging   flags.
  4608.              (Mnemonic: value of -D switch.)
  4609.  
  4610.      $^F     The maximum system file  descriptor,  ordinarily  2.
  4611.              System  file descriptors are passed to subprocesses,
  4612.              while higher file descriptors are  not.   During  an
  4613.              open,  system file descriptors are preserved even if
  4614.              the  open  fails.   Ordinary  file  descriptors  are
  4615.              closed before the open is attempted.
  4616.  
  4617.      $^I     The current value  of  the  inplace-edit  extension.
  4618.              Use  undef  to  disable inplace editing.  (Mnemonic:
  4619.              value of -i switch.)
  4620.  
  4621.      $^P     The internal flag that the debugger clears  so  that
  4622.              it doesn't debug itself.  You could conceivable dis-
  4623.              able debugging yourself by clearing it.
  4624.  
  4625.      $^T     The time at  which  the  script  began  running,  in
  4626.              seconds since the epoch.  The values returned by the
  4627.              -M , -A and -C filetests are based on this value.
  4628.  
  4629.      $^W     The current value of the warning switch.  (Mnemonic:
  4630.              related to the -w switch.)
  4631.  
  4632.      $^X     The name that Perl  itself  was  executed  as,  from
  4633.              argv[0].
  4634.  
  4635.      $ARGV   contains the name of the current file  when  reading
  4636.              from <>.
  4637.  
  4638.      @ARGV   The array ARGV contains the command  line  arguments
  4639.              intended  for  the  script.  Note that $#ARGV is the
  4640.              generally  number  of  arguments  minus  one,  since
  4641.              $ARGV[0]  is  the  first  argument,  NOT the command
  4642.              name.  See $0 for the command name.
  4643.  
  4644.      @INC    The array INC contains the list of  places  to  look
  4645.              for  perl  scripts  to be evaluated by the "do EXPR"
  4646.              command or the "require" command.  It initially con-
  4647.              sists  of  the  arguments  to  any  -I  command line
  4648.              switches, followed  by  the  default  perl  library,
  4649.              probably  "/usr/local/lib/perl", followed by ".", to
  4650.              represent the current directory.
  4651.  
  4652.      %INC    The associative array INC contains entries for  each
  4653.              filename   that   has  been  included  via  "do"  or
  4654.              "require".  The key is the filename  you  specified,
  4655.              and  the  value is the location of the file actually
  4656.              found.  The "require" command  uses  this  array  to
  4657.              determine  whether  a  given  file  has already been
  4658.              included.
  4659.  
  4660.      $ENV{expr}
  4661.              The associative  array  ENV  contains  your  current
  4662.              environment.   Setting  a  value  in ENV changes the
  4663.              environment for child processes.
  4664.  
  4665.      $SIG{expr}
  4666.              The associative array SIG  is  used  to  set  signal
  4667.              handlers for various signals.  Example:
  4668.  
  4669.                   sub handler {  # 1st argument is signal name
  4670.                        local($sig) = @_;
  4671.                        print "Caught a SIG$sig--shutting down\n";
  4672.                        close(LOG);
  4673.                        exit(0);
  4674.                   }
  4675.  
  4676.                   $SIG{'INT'} = 'handler';
  4677.                   $SIG{'QUIT'} = 'handler';
  4678.                   ...
  4679.                   $SIG{'INT'} = 'DEFAULT'; # restore default action
  4680.                   $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
  4681.  
  4682.              The SIG array only contains values for  the  signals
  4683.              actually set within the perl script.
  4684.  
  4685.      Packages
  4686.  
  4687.      Perl provides a mechanism for alternate namespaces  to  pro-
  4688.      tect  packages  from  stomping on each others variables.  By
  4689.      default, a perl script starts  compiling  into  the  package
  4690.      known as "main".  By use of the package declaration, you can
  4691.      switch namespaces.  The scope of the package declaration  is
  4692.      from  the  declaration  itself  to  the end of the enclosing
  4693.      block (the same scope as the local()  operator).   Typically
  4694.      it  would  be the first declaration in a file to be included
  4695.      by the "require" operator.  You can switch into a package in
  4696.      more than one place; it merely influences which symbol table
  4697.      is used by the compiler for the rest of that block.  You can
  4698.      refer to variables and filehandles in other packages by pre-
  4699.      fixing the identifier with the package  name  and  a  single
  4700.      quote.   If  the package name is null, the "main" package as
  4701.      assumed.
  4702.  
  4703.      Only identifiers starting with letters  are  stored  in  the
  4704.      packages  symbol table.  All other symbols are kept in pack-
  4705.      age "main".  In addition,  the  identifiers  STDIN,  STDOUT,
  4706.      STDERR,  ARGV, ARGVOUT, ENV, INC and SIG are forced to be in
  4707.      package "main", even when used for other purposes than their
  4708.      built-in  one.  Note also that, if you have a package called
  4709.      "m", "s" or "y", the you can't use the qualified form of  an
  4710.      identifier since it will be interpreted instead as a pattern
  4711.      match, a substitution or a translation.
  4712.  
  4713.      Eval'ed strings are compiled in the  package  in  which  the
  4714.      eval  was  compiled  in.   (Assignments  to $SIG{}, however,
  4715.      assume the signal handler specified is in the main  package.
  4716.      Qualify the signal handler name if you wish to have a signal
  4717.      handler in a package.) For an example, examine perldb.pl  in
  4718.      the  perl  library.  It initially switches to the DB package
  4719.      so that the debugger doesn't interfere with variables in the
  4720.      script you are trying to debug.  At various points, however,
  4721.      it temporarily switches back to the main package to evaluate
  4722.      various expressions in the context of the main package.
  4723.  
  4724.      The symbol table for a package happens to be stored  in  the
  4725.      associative array of that name prepended with an underscore.
  4726.      The value in each entry of the associative array is what you
  4727.      are  referring to when you use the *name notation.  In fact,
  4728.      the following have the same effect (in  package  main,  any-
  4729.      way), though the first is more efficient because it does the
  4730.      symbol table lookups at compile time:
  4731.  
  4732.           local(*foo) = *bar;
  4733.           local($_main{'foo'}) = $_main{'bar'};
  4734.  
  4735.      You can use this to print out all the variables in  a  pack-
  4736.      age,  for  instance.   Here  is  dumpvar.pl  from  the  perl
  4737.      library:
  4738.  
  4739.           package dumpvar;
  4740.  
  4741.           sub main'dumpvar {
  4742.               ($package) = @_;
  4743.               local(*stab) = eval("*_$package");
  4744.               while (($key,$val) = each(%stab)) {
  4745.                   {
  4746.                       local(*entry) = $val;
  4747.                       if (defined $entry) {
  4748.                           print "\$$key = '$entry'\n";
  4749.                       }
  4750.                       if (defined @entry) {
  4751.                           print "\@$key = (\n";
  4752.                           foreach $num ($[ .. $#entry) {
  4753.                               print "  $num\t'",$entry[$num],"'\n";
  4754.                           }
  4755.                           print ")\n";
  4756.                       }
  4757.                       if ($key ne "_$package" && defined %entry) {
  4758.                           print "\%$key = (\n";
  4759.                           foreach $key (sort keys(%entry)) {
  4760.                               print "  $key\t'",$entry{$key},"'\n";
  4761.                           }
  4762.                           print ")\n";
  4763.                       }
  4764.                   }
  4765.               }
  4766.           }
  4767.  
  4768.      Note that, even though the subroutine is compiled in package
  4769.      dumpvar, the name of the subroutine is qualified so that its
  4770.      name is inserted into package "main".
  4771.  
  4772.      Style
  4773.  
  4774.      Each programmer will, of course, have his or her own prefer-
  4775.      ences  in  regards to formatting, but there are some general
  4776.      guidelines that will make your programs easier to read.
  4777.  
  4778.      1.  Just because you  CAN  do  something  a  particular  way
  4779.          doesn't  mean  that  you SHOULD do it that way.  Perl is
  4780.          designed to give you several ways  to  do  anything,  so
  4781.          consider picking the most readable one.  For instance
  4782.  
  4783.               open(FOO,$foo) || die "Can't open $foo: $!";
  4784.  
  4785.          is better than
  4786.  
  4787.               die "Can't open $foo: $!" unless open(FOO,$foo);
  4788.  
  4789.          because the second way  hides  the  main  point  of  the
  4790.          statement in a modifier.  On the other hand
  4791.  
  4792.               print "Starting analysis\n" if $verbose;
  4793.  
  4794.          is better than
  4795.  
  4796.               $verbose && print "Starting analysis\n";
  4797.  
  4798.          since the main point isn't whether the user typed -v  or
  4799.          not.
  4800.  
  4801.          Similarly, just because  an  operator  lets  you  assume
  4802.          default arguments doesn't mean that you have to make use
  4803.          of the defaults.  The defaults are there for  lazy  sys-
  4804.          tems programmers writing one-shot programs.  If you want
  4805.          your program to  be  readable,  consider  supplying  the
  4806.          argument.
  4807.  
  4808.          Along  the  same  lines,  just  because  you  can   omit
  4809.          parentheses  in  many places doesn't mean that you ought
  4810.          to:
  4811.  
  4812.               return print reverse sort num values array;
  4813.               return print(reverse(sort num (values(%array))));
  4814.  
  4815.          When in doubt, parenthesize.  At the very least it  will
  4816.          let some poor schmuck bounce on the % key in vi.
  4817.  
  4818.          Even if you aren't in doubt, consider the mental welfare
  4819.          of  the  person  who has to maintain the code after you,
  4820.          and who will probably put parens in the wrong place.
  4821.  
  4822.      2.  Don't go through silly contortions to exit a loop at the
  4823.          top  or the bottom, when perl provides the "last" opera-
  4824.          tor so you can exit in the middle.  Just  outdent  it  a
  4825.          little to make it more visible:
  4826.  
  4827.              line:
  4828.               for (;;) {
  4829.                   statements;
  4830.               last line if $foo;
  4831.                   next line if /^#/;
  4832.                   statements;
  4833.               }
  4834.  
  4835.      3.  Don't be afraid to use  loop  labels--they're  there  to
  4836.          enhance readability as well as to allow multi-level loop
  4837.          breaks.  See last example.
  4838.  
  4839.      4.  For portability, when using features  that  may  not  be
  4840.          implemented  on  every machine, test the construct in an
  4841.          eval to see if it fails.  If you know  what  version  or
  4842.          patchlevel a particular feature was implemented, you can
  4843.          test $] to see if it will be there.
  4844.  
  4845.      5.  Choose mnemonic identifiers.
  4846.  
  4847.      6.  Be consistent.
  4848.  
  4849.      Debugging
  4850.  
  4851.      If you invoke perl with a -d switch, your script will be run
  4852.      under  a  debugging  monitor.  It will halt before the first
  4853.      executable statement and ask you for a command, such as:
  4854.  
  4855.      h           Prints out a help message.
  4856.  
  4857.      T           Stack trace.
  4858.  
  4859.      s           Single step.   Executes  until  it  reaches  the
  4860.                  beginning of another statement.
  4861.  
  4862.      n           Next.  Executes over subroutine calls, until  it
  4863.                  reaches the beginning of the next statement.
  4864.  
  4865.      f           Finish.  Executes statements until it  has  fin-
  4866.                  ished the current subroutine.
  4867.  
  4868.      c           Continue.  Executes until the next breakpoint is
  4869.                  reached.
  4870.  
  4871.      c line      Continue to the specified line.  Inserts a  one-
  4872.                  time-only breakpoint at the specified line.
  4873.  
  4874.      <CR>        Repeat last n or s.
  4875.  
  4876.      l min+incr  List incr+1 lines starting at min.   If  min  is
  4877.                  omitted, starts where last listing left off.  If
  4878.                  incr is omitted, previous value of incr is used.
  4879.  
  4880.      l min-max   List lines in the indicated range.
  4881.  
  4882.      l line      List just the indicated line.
  4883.  
  4884.      l           List next window.
  4885.  
  4886.      -           List previous window.
  4887.  
  4888.      w line      List window around line.
  4889.  
  4890.      l subname   List subroutine.  If it's a long  subroutine  it
  4891.                  just lists the beginning.  Use "l" to list more.
  4892.  
  4893.      /pattern/   Regular expression search forward  for  pattern;
  4894.                  the final / is optional.
  4895.  
  4896.      ?pattern?   Regular expression search backward for  pattern;
  4897.                  the final ? is optional.
  4898.  
  4899.      L           List lines that have breakpoints or actions.
  4900.  
  4901.      S           Lists the names of all subroutines.
  4902.  
  4903.      t           Toggle trace mode on or off.
  4904.  
  4905.      b line condition
  4906.                  Set a breakpoint.  If line is  omitted,  sets  a
  4907.                  breakpoint  on the line that is about to be exe-
  4908.                  cuted.  If  a  condition  is  specified,  it  is
  4909.                  evaluated each time the statement is reached and
  4910.                  a breakpoint is taken only if the  condition  is
  4911.                  true.  Breakpoints may only be set on lines that
  4912.                  begin an executable statement.
  4913.  
  4914.      b subname condition
  4915.                  Set breakpoint at first executable line of  sub-
  4916.                  routine.
  4917.  
  4918.      d line      Delete breakpoint.  If line is omitted,  deletes
  4919.                  the  breakpoint  on the line that is about to be
  4920.                  executed.
  4921.  
  4922.      D           Delete all breakpoints.
  4923.  
  4924.      a line command
  4925.                  Set an action for line.   A  multi-line  command
  4926.                  may be entered by backslashing the newlines.
  4927.  
  4928.      A           Delete all line actions.
  4929.  
  4930.      < command   Set an action to happen  before  every  debugger
  4931.                  prompt.   A multi-line command may be entered by
  4932.                  backslashing the newlines.
  4933.  
  4934.      > command   Set an action to happen after  the  prompt  when
  4935.                  you've just given a command to return to execut-
  4936.                  ing the script.  A  multi-line  command  may  be
  4937.                  entered by backslashing the newlines.
  4938.  
  4939.      V package   List all variables in package.  Default is  main
  4940.                  package.
  4941.  
  4942.      ! number    Redo a debugging command.  If number is omitted,
  4943.                  redoes the previous command.
  4944.  
  4945.      ! -number   Redo the command that  was  that  many  commands
  4946.                  ago.
  4947.  
  4948.      H -number   Display last n commands.  Only  commands  longer
  4949.                  than  one  character  are  listed.  If number is
  4950.                  omitted, lists them all.
  4951.  
  4952.      q or ^D     Quit.
  4953.  
  4954.      command     Execute command as a perl statement.  A  missing
  4955.                  semicolon will be supplied.
  4956.  
  4957.      p expr      Same  as  "print  DB'OUT  expr".    The   DB'OUT
  4958.                  filehandle  is opened to /dev/tty, regardless of
  4959.                  where STDOUT may be redirected to.
  4960.  
  4961.      If you want to modify the debugger, copy perldb.pl from  the
  4962.      perl  library  to  your  current  directory and modify it as
  4963.      necessary.  (You'll also have to put  -I.  on  your  command
  4964.      line.) You can do some customization by setting up a .perldb
  4965.      file which contains initialization code.  For instance,  you
  4966.      could make aliases like these:
  4967.  
  4968.          $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
  4969.          $DB'alias{'stop'} = 's/^stop (at|in)/b/';
  4970.          $DB'alias{'.'} =
  4971.            's/^\./p "\$DB\'sub(\$DB\'line):\t",\$DB\'line[\$DB\'line]/';
  4972.  
  4973.      Setuid Scripts
  4974.  
  4975.      Perl is designed to make it easy to write secure setuid  and
  4976.      setgid  scripts.  Unlike shells, which are based on multiple
  4977.      substitution passes on each line of the script, perl uses  a
  4978.      more   conventional  evaluation  scheme  with  fewer  hidden
  4979.      "gotchas".   Additionally,  since  the  language  has   more
  4980.      built-in  functionality,  it  has to rely less upon external
  4981.      (and possibly untrustworthy) programs to accomplish its pur-
  4982.      poses.
  4983.  
  4984.      In an unpatched 4.2 or 4.3bsd  kernel,  setuid  scripts  are
  4985.      intrinsically  insecure, but this kernel feature can be dis-
  4986.      abled.  If it is, perl can emulate  the  setuid  and  setgid
  4987.      mechanism  when  it notices the otherwise useless setuid/gid
  4988.      bits on perl scripts.  If the kernel feature isn't disabled,
  4989.      perl  will  complain  loudly  that  your  setuid  script  is
  4990.      insecure.  You'll need to either disable the  kernel  setuid
  4991.      script feature, or put a C wrapper around the script.
  4992.  
  4993.      When perl is executing a setuid  script,  it  takes  special
  4994.      precautions  to  prevent  you  from falling into any obvious
  4995.      traps.  (In some ways, a perl script is more secure than the
  4996.      corresponding   C   program.)  Any  command  line  argument,
  4997.      environment variable, or input is marked as  "tainted",  and
  4998.      may not be used, directly or indirectly, in any command that
  4999.      invokes a subshell, or in any command that  modifies  files,
  5000.      directories  or  processes.  Any variable that is set within
  5001.      an expression that has previously referenced a tainted value
  5002.      also becomes tainted (even if it is logically impossible for
  5003.      the tainted value to influence the variable).  For example:
  5004.  
  5005.           $foo = shift;            # $foo is tainted
  5006.           $bar = $foo,'bar';       # $bar is also tainted
  5007.           $xxx = <>;               # Tainted
  5008.           $path = $ENV{'PATH'};    # Tainted, but see below
  5009.           $abc = 'abc';            # Not tainted
  5010.  
  5011.           system "echo $foo";      # Insecure
  5012.           system "/bin/echo", $foo;     # Secure (doesn't use sh)
  5013.           system "echo $bar";      # Insecure
  5014.           system "echo $abc";      # Insecure until PATH set
  5015.  
  5016.           $ENV{'PATH'} = '/bin:/usr/bin';
  5017.           $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  5018.  
  5019.           $path = $ENV{'PATH'};    # Not tainted
  5020.           system "echo $abc";      # Is secure now!
  5021.  
  5022.           open(FOO,"$foo");        # OK
  5023.           open(FOO,">$foo");       # Not OK
  5024.  
  5025.           open(FOO,"echo $foo|");  # Not OK, but...
  5026.           open(FOO,"-|") || exec 'echo', $foo;    # OK
  5027.  
  5028.           $zzz = `echo $foo`;      # Insecure, zzz tainted
  5029.  
  5030.           unlink $abc,$foo;        # Insecure
  5031.           umask $foo;              # Insecure
  5032.  
  5033.           exec "echo $foo";        # Insecure
  5034.           exec "echo", $foo;       # Secure (doesn't use sh)
  5035.           exec "sh", '-c', $foo;   # Considered secure, alas
  5036.  
  5037.      The taintedness is associated with  each  scalar  value,  so
  5038.      some elements of an array can be tainted, and others not.
  5039.  
  5040.      If you try to do something insecure, you will  get  a  fatal
  5041.      error   saying   something  like  "Insecure  dependency"  or
  5042.      "Insecure PATH".  Note that you can still write an  insecure
  5043.      system  call or exec, but only by explicitly doing something
  5044.      like the last example above.  You can also bypass the taint-
  5045.      ing mechanism by referencing subpatterns--perl presumes that
  5046.      if you reference a substring using $1,  $2,  etc,  you  knew
  5047.      what you were doing when you wrote the pattern:
  5048.  
  5049.           $ARGV[0] =~ /^-P(\w+)$/;
  5050.           $printer = $1;      # Not tainted
  5051.  
  5052.      This is fairly secure since \w+ doesn't  match  shell  meta-
  5053.      characters.   Use  of  .+ would have been insecure, but perl
  5054.      doesn't check for that, so you must  be  careful  with  your
  5055.      patterns.   This  is  the ONLY mechanism for untainting user
  5056.      supplied filenames if you want to do file operations on them
  5057.      (unless you make $> equal to $<).
  5058.  
  5059.      It's also possible to get into trouble with other operations
  5060.      that don't care whether they use tainted values.  Make judi-
  5061.      cious use of the  file  tests  in  dealing  with  any  user-
  5062.      supplied  filenames.  When possible, do opens and such after
  5063.      setting $> = $<.  Perl  doesn't  prevent  you  from  opening
  5064.      tainted  filenames for reading, so be careful what you print
  5065.      out.  The tainting mechanism is intended to  prevent  stupid
  5066.      mistakes, not to remove the need for thought.
  5067.  
  5068. ENVIRONMENT
  5069.      Perl uses PATH in executing subprocesses, and in finding the
  5070.      script  if -S is used.  HOME or LOGDIR are used if chdir has
  5071.      no argument.
  5072.  
  5073.      Apart from these, perl uses no environment variables, except
  5074.      to  make them available to the script being executed, and to
  5075.      child processes.  However, scripts running setuid  would  do
  5076.      well  to  execute  the following lines before doing anything
  5077.      else, just to keep people honest:
  5078.  
  5079.          $ENV{'PATH'} = '/bin:/usr/bin';    # or whatever you need
  5080.          $ENV{'SHELL'} = '/bin/sh' if $ENV{'SHELL'} ne '';
  5081.          $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  5082.  
  5083. AUTHOR
  5084.      Larry Wall <lwall@netlabs.com>
  5085.      MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk>
  5086.      Macintosh port by Matthias Neeracher <neeri@iis.ee.ethz.ch>
  5087.  
  5088. FILES
  5089.      /tmp/perl-eXXXXXX   temporary file for -e commands.
  5090.  
  5091. SEE ALSO
  5092.      a2p  awk to perl translator
  5093.      s2p  sed to perl translator
  5094.  
  5095. DIAGNOSTICS
  5096.      Compilation errors will tell you  the  line  number  of  the
  5097.      error,  with  an  indication of the next token or token type
  5098.      that was to be examined.  (In the case of a script passed to
  5099.      perl via -e switches, each -e is counted as one line.)
  5100.  
  5101.      Setuid scripts have additional constraints that can  produce
  5102.      error  messages such as "Insecure dependency".  See the sec-
  5103.      tion on setuid scripts.
  5104.  
  5105. TRAPS
  5106.      Accustomed awk users should take special note of the follow-
  5107.      ing:
  5108.  
  5109.      *   Semicolons are required after all simple  statements  in
  5110.          perl.  Newline is not a statement delimiter.
  5111.  
  5112.      *   Curly brackets are required on ifs and whiles.
  5113.  
  5114.      *   Variables begin with $ or @ in perl.
  5115.  
  5116.      *   Arrays index from 0 unless you set $[.  Likewise  string
  5117.          positions in substr() and index().
  5118.  
  5119.      *   You have to decide whether your  array  has  numeric  or
  5120.          string indices.
  5121.  
  5122.      *   Associative array values do not  spring  into  existence
  5123.          upon mere reference.
  5124.  
  5125.      *   You have to decide whether you want  to  use  string  or
  5126.          numeric comparisons.
  5127.  
  5128.      *   Reading an input line does not split it  for  you.   You
  5129.          get  to  split  it  yourself to an array.  And the split
  5130.          operator has different arguments.
  5131.  
  5132.      *   The current input line is normally in $_,  not  $0.   It
  5133.          generally  does  not  have the newline stripped.  ($0 is
  5134.          the name of the program executed.)
  5135.  
  5136.      *   $<digit> does not refer to  fields--it  refers  to  sub-
  5137.          strings matched by the last match pattern.
  5138.  
  5139.      *   The print  statement  does  not  add  field  and  record
  5140.          separators unless you set $, and $\.
  5141.  
  5142.      *   You must open your files before you print to them.
  5143.  
  5144.      *   The range operator  is  "..",  not  comma.   (The  comma
  5145.          operator works as in C.)
  5146.  
  5147.      *   The match operator is "=~", not "~".  ("~" is the  one's
  5148.          complement operator, as in C.)
  5149.  
  5150.      *   The exponentiation operator is "**", not "^".   ("^"  is
  5151.          the XOR operator, as in C.)
  5152.  
  5153.      *   The concatenation operator is ".", not the null  string.
  5154.          (Using  the  null  string  would  render  "/pat/  /pat/"
  5155.          unparsable, since the third slash would  be  interpreted
  5156.          as  a division operator--the tokener is in fact slightly
  5157.          context sensitive for operators like /, ?, and  <.   And
  5158.          in fact, . itself can be the beginning of a number.)
  5159.  
  5160.      *   Next, exit and continue work differently.
  5161.  
  5162.      *   The following variables work differently
  5163.  
  5164.                 Awk               Perl
  5165.                 ARGC              $#ARGV
  5166.                 ARGV[0]           $0
  5167.                 FILENAME          $ARGV
  5168.                 FNR               $. - something
  5169.                 FS                (whatever you like)
  5170.                 NF                $#Fld, or some such
  5171.                 NR                $.
  5172.                 OFMT              $#
  5173.                 OFS               $,
  5174.                 ORS               $\
  5175.                 RLENGTH           length($&)
  5176.                 RS                $/
  5177.                 RSTART            length($`)
  5178.                 SUBSEP            $;
  5179.  
  5180.      *   When in doubt, run the awk construct through a2p and see
  5181.          what it gives you.
  5182.  
  5183.      Cerebral C programmers should take note of the following:
  5184.  
  5185.      *   Curly brackets are required on ifs and whiles.
  5186.  
  5187.      *   You should use "elsif" rather than "else if"
  5188.  
  5189.      *   Break and continue become last and next, respectively.
  5190.  
  5191.      *   There's no switch statement.
  5192.  
  5193.      *   Variables begin with $ or @ in perl.
  5194.  
  5195.      *   Printf does not implement *.
  5196.  
  5197.      *   Comments begin with #, not /*.
  5198.  
  5199.      *   You can't take the address of anything.
  5200.  
  5201.      *   ARGV must be capitalized.
  5202.  
  5203.      *   The "system" calls link,  unlink,  rename,  etc.  return
  5204.          nonzero for success, not 0.
  5205.  
  5206.      *   Signal handlers deal with signal names, not numbers.
  5207.  
  5208.      Seasoned sed programmers should take note of the following:
  5209.  
  5210.      *   Backreferences in substitutions use $ rather than \.
  5211.  
  5212.      *   The pattern matching metacharacters (, ), and |  do  not
  5213.          have backslashes in front.
  5214.  
  5215.      *   The range operator is .. rather than comma.
  5216.  
  5217.      Sharp shell programmers should take note of the following:
  5218.  
  5219.      *   The  backtick  operator  does  variable   interpretation
  5220.          without  regard  to the presence of single quotes in the
  5221.          command.
  5222.  
  5223.      *   The backtick operator does no translation of the  return
  5224.          value, unlike csh.
  5225.  
  5226.      *   Shells (especially csh) do several levels  of  substitu-
  5227.          tion  on each command line.  Perl does substitution only
  5228.          in certain constructs such as double quotes,  backticks,
  5229.          angle brackets and search patterns.
  5230.  
  5231.      *   Shells interpret scripts a little bit at a  time.   Perl
  5232.          compiles the whole program before executing it.
  5233.  
  5234.      *   The arguments are available via @ARGV, not $1, $2, etc.
  5235.  
  5236.      *   The environment is not automatically made  available  as
  5237.          variables.
  5238.  
  5239. ERRATA AND ADDENDA
  5240.      The Perl book, Programming Perl , has  the  following  omis-
  5241.      sions and goofs.
  5242.  
  5243.      On page 5, the examples which read
  5244.  
  5245.           eval "/usr/bin/perl
  5246.  
  5247.      should read
  5248.  
  5249.           eval "exec /usr/bin/perl
  5250.  
  5251.      On page 195, the equivalent to the System V sum program only
  5252.      works for very small files.  To do larger files, use
  5253.  
  5254.           undef $/;
  5255.  
  5256.           $checksum = unpack("%32C*",<>) % 32767;
  5257.  
  5258.      The  descriptions  of  alarm  and  sleep  refer  to   signal
  5259.      SIGALARM.  These should refer to SIGALRM.
  5260.  
  5261.      The -0 switch to set the initial value of $/  was  added  to
  5262.      Perl after the book went to press.
  5263.  
  5264.      The -l switch now does automatic line ending processing.
  5265.  
  5266.      The qx// construct is now a synonym for backticks.
  5267.  
  5268.      $0 may now be assigned to set the argument displayed  by  ps
  5269.      (1).
  5270.  
  5271.      The new @###.## format was  omitted  accidentally  from  the
  5272.      description on formats.
  5273.  
  5274.      It wasn't known at press time that  s///ee  caused  multiple
  5275.      evaluations  of  the  replacement expression.  This is to be
  5276.      construed as a feature.
  5277.  
  5278.      (LIST) x $count now does array replication.
  5279.  
  5280.      There is now no limit on the number of parentheses in a reg-
  5281.      ular expression.
  5282.  
  5283.      In double-quote context, more escapes are supported: \e, \a,
  5284.      \x1b,  \c[,  \l,  \L,  \u,  \U, \E.  The latter five control
  5285.      up/lower case translation.
  5286.  
  5287.      The $/ variable may now be set to a  multi-character  delim-
  5288.      iter.
  5289.  
  5290.      There is now a g modifier on ordinary pattern matching  that
  5291.      causes  it  to  iterate  through  a  string finding multiple
  5292.      matches.
  5293.  
  5294.      All of the $^X variables are new except for $^T.
  5295.  
  5296.      The  default  top-of-form  format  for  FILEHANDLE  is   now
  5297.      FILEHANDLE_TOP rather than top.
  5298.  
  5299.      The eval {} and sort {} constructs  were  added  in  version
  5300.      4.018.
  5301.  
  5302.      The v and V (little-endian) template options  for  pack  and
  5303.      unpack were added in 4.019.
  5304.  
  5305. BUGS
  5306.      Perl is at the mercy of your machine's definitions of  vari-
  5307.      ous operations such as type casting, atof() and sprintf().
  5308.  
  5309.      If your stdio requires an seek  or  eof  between  reads  and
  5310.      writes  on a particular stream, so does perl.  (This doesn't
  5311.      apply to sysread() and syswrite().)
  5312.  
  5313.      While none of the built-in data  types  have  any  arbitrary
  5314.      size  limits (apart from memory size), there are still a few
  5315.      arbitrary limits: a given identifier may not be longer  than
  5316.      255  characters, and no component of your PATH may be longer
  5317.      than 255 if you use -S.
  5318.  
  5319.      Perl actually stands  for  Pathologically  Eclectic  Rubbish
  5320.      Lister, but don't tell anyone I said that.
  5321.  
  5322.