home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / perl / perl30 / perl.man < prev    next >
Text File  |  1994-06-04  |  217KB  |  6,202 lines

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