home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / perl / os2perl / perl.man < prev    next >
Text File  |  1991-06-18  |  223KB  |  5,517 lines

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