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