home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / perl / perl40 / perlman.txt < prev    next >
Text File  |  1993-03-14  |  207KB  |  5,210 lines

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