home *** CD-ROM | disk | FTP | other *** search
/ Club Amiga de Montreal - CAM / CAM_CD_1.iso / files / 152.lha / perl.cat < prev    next >
Text File  |  1988-04-26  |  79KB  |  1,566 lines

  1. PERL(1)             UNIX Programmer's Manual              PERL(1)
  2. NAME
  3.      perl - Practical Extraction and Report Language
  4. SYNOPSIS
  5.      perl [options] filename args
  6. DESCRIPTION
  7.      Perl is a interpreted language optimized for scanning arbi-
  8.      trary text files, extracting information from those text
  9.      files, and printing reports based on that information.  It's
  10.      also a good language for many system management tasks.  The
  11.      language is intended to be practical (easy to use, effi-
  12.      cient, complete) rather than beautiful (tiny, elegant,
  13.      minimal).  It combines (in the author's opinion, anyway)
  14.      some of the best features of C, sed, awk, and sh, so people
  15.      familiar with those languages should have little difficulty
  16.      with it.  (Language historians will also note some vestiges
  17.      of csh, Pascal, and even BASIC-PLUS.) Expression syntax
  18.      corresponds quite closely to C expression syntax.  If you
  19.      have a problem that would ordinarily use sed or awk or sh,
  20.      but it exceeds their capabilities or must run a little fas-
  21.      ter, and you don't want to write the silly thing in C, then
  22.      perl may be for you.  There are also translators to turn
  23.      your sed and awk scripts into perl scripts.  OK, enough
  24.      hype.
  25.      Upon startup, perl looks for your script in one of the fol-
  26.      lowing places:
  27.      1.  Specified line by line via -e switches on the command
  28.          line.
  29.      2.  Contained in the file specified by the first filename on
  30.          the command line.  (Note that systems supporting the #!
  31.          notation invoke interpreters this way.)
  32.      3.  Passed in via standard input.
  33.      After locating your script, perl compiles it to an internal
  34.      form.  If the script is syntactically correct, it is exe-
  35.      cuted.
  36.      Options
  37.      Note: on first reading this section may not make much sense
  38.      to you.  It's here at the front for easy reference.
  39.      A single-character option may be combined with the following
  40.      option, if any.  This is particularly useful when invoking a
  41.      script using the #! construct which only allows one argu-
  42.      ment.  Example:
  43.  
  44. Printed 7/26/88               LOCAL                             1
  45. PERL(1)             UNIX Programmer's Manual              PERL(1)
  46.           #!/bin/perl -spi.bak     # same as -s -p -i.bak
  47.           ...
  48.      Options include:
  49.      -D<number>
  50.           sets debugging flags.  To watch how it executes your
  51.           script, use -D14. (This only works if debugging is com-
  52.           piled into your perl.)
  53.  
  54.      -e commandline
  55.           may be used to enter one line of script.  Multiple -e
  56.           commands may be given to build up a multi-line script.
  57.           If -e is given, perl will not look for a script
  58.           filename in the argument list.
  59.      -i<extension>
  60.           specifies that files processed by the <> construct are
  61.           to be edited in-place.  It does this by renaming the
  62.           input file, opening the output file by the same name,
  63.           and selecting that output file as the default for print
  64.           statements.  The extension, if supplied, is added to
  65.           the name of the old file to make a backup copy.  If no
  66.           extension is supplied, no backup is made.  Saying "perl
  67.           -p -i.bak -e "s/foo/bar/;" ... " is the same as using
  68.           the script:
  69.                #!/bin/perl -pi.bak
  70.                s/foo/bar/;
  71.           which is equivalent to
  72.                #!/bin/perl
  73.                while (<>) {
  74.                     if ($ARGV ne $oldargv) {
  75.                          rename($ARGV,$ARGV . '.bak');
  76.                          open(ARGVOUT,">$ARGV");
  77.                          select(ARGVOUT);
  78.                          $oldargv = $ARGV;
  79.                     }
  80.                     s/foo/bar/;
  81.                }
  82.                continue {
  83.                    print;     # this prints to original filename
  84.                }
  85.                select(stdout);
  86.           except that the -i form doesn't need to compare $ARGV
  87.           to $oldargv to know when the filename has changed.  It
  88.           does, however, use ARGVOUT for the selected filehandle.
  89.           Note that stdout is restored as the default output
  90.           filehandle after the loop.
  91. Printed 7/26/88               LOCAL                             2
  92. PERL(1)             UNIX Programmer's Manual              PERL(1)
  93.      -I<directory>
  94.           may be used in conjunction with -P to tell the C
  95.           preprocessor where to look for include files.  By
  96.           default /usr/include and /usr/lib/perl are searched.
  97.      -n   causes perl to assume the following loop around your
  98.           script, which makes it iterate over filename arguments
  99.           somewhat like "sed -n" or awk:
  100.                while (<>) {
  101.                     ...       # your script goes here
  102.                }
  103.  
  104.           Note that the lines are not printed by default.  See -p
  105.           to have lines printed.
  106.      -p   causes perl to assume the following loop around your
  107.           script, which makes it iterate over filename arguments
  108.           somewhat like sed:
  109.                while (<>) {
  110.                     ...       # your script goes here
  111.                } continue {
  112.                     print;
  113.                }
  114.           Note that the lines are printed automatically.  To
  115.           suppress printing use the -n switch.  A -p overrides a
  116.           -n switch.
  117.      -P   causes your script to be run through the C preprocessor
  118.           before compilation by perl. (Since both comments and
  119.           cpp directives begin with the # character, you should
  120.           avoid starting comments with any words recognized by
  121.           the C preprocessor such as "if", "else" or "define".)
  122.  
  123.      -s   enables some rudimentary switch parsing for switches on
  124.           the command line after the script name but before any
  125.           filename arguments (or before a --).  Any switch found
  126.           there is removed from @ARGV and sets the corresponding
  127.           variable in the perl script.  The following script
  128.           prints "true" if and only if the script is invoked with
  129.           a -xyz switch.
  130.                #!/bin/perl -s
  131.                if ($xyz) { print "true\n"; }
  132.      -v   prints the version and patchlevel of your perl execut-
  133.           able.
  134. Printed 7/26/88               LOCAL                             3
  135.  
  136. PERL(1)             UNIX Programmer's Manual              PERL(1)
  137.      Data Types and Objects
  138.      Perl has about two and a half data types: strings, arrays of
  139.      strings, and associative arrays.  Strings and arrays of
  140.      strings are first class objects, for the most part, in the
  141.      sense that they can be used as a whole as values in an
  142.      expression.  Associative arrays can only be accessed on an
  143.      association by association basis; they don't have a value as
  144.      a whole (at least not yet).
  145.      Strings are interpreted numerically as appropriate.  A
  146.      string is interpreted as TRUE in the boolean sense if it is
  147.      not the null string or 0.  Booleans returned by operators
  148.      are 1 for true and '0' or '' (the null string) for false.
  149.      References to string variables always begin with '$', even
  150.      when referring to a string that is part of an array.  Thus:
  151.          $days           # a simple string variable
  152.          $days[28]       # 29th element of array @days
  153.          $days{'Feb'}    # one value from an associative array
  154.      but entire arrays are denoted by '@':
  155.          @days           # ($days[0], $days[1],... $days[n])
  156.      Any of these four constructs may be assigned to (in compiler
  157.      lingo, may serve as an lvalue).  (Additionally, you may find
  158.      the length of array @days by evaluating "$#days", as in csh.
  159.      [Actually, it's not the length of the array, it's the sub-
  160.      script of the last element, since there is (ordinarily) a
  161.      0th element.])
  162.      Every data type has its own namespace.  You can, without
  163.      fear of conflict, use the same name for a string variable,
  164.      an array, an associative array, a filehandle, a subroutine
  165.      name, and/or a label.  Since variable and array references
  166.      always start with '$' or '@', the "reserved" words aren't in
  167.      fact reserved with respect to variable names.  (They ARE
  168.      reserved with respect to labels and filehandles, however,
  169.      which don't have an initial special character.) Case IS
  170.      significant--"FOO", "Foo" and "foo" are all different names.
  171.      Names which start with a letter may also contain digits and
  172.      underscores.  Names which do not start with a letter are
  173.      limited to one character, e.g. "$%" or "$$".  (Many one
  174.      character names have a predefined significance to perl. More
  175.      later.)
  176.      String literals are delimited by either single or double
  177.      quotes.  They work much like shell quotes: double-quoted
  178.      string literals are subject to backslash and variable
  179. Printed 7/26/88               LOCAL                             4
  180.  
  181. PERL(1)             UNIX Programmer's Manual              PERL(1)
  182.      substitution; single-quoted strings are not.  The usual
  183.      backslash rules apply for making characters such as newline,
  184.      tab, etc.  You can also embed newlines directly in your
  185.      strings, i.e. they can end on a different line than they
  186.      begin.  This is nice, but if you forget your trailing quote,
  187.      the error will not be reported until perl finds another line
  188.      containing the quote character, which may be much further on
  189.      in the script.  Variable substitution inside strings is lim-
  190.      ited (currently) to simple string variables.  The following
  191.      code segment prints out "The price is $100."
  192.          $Price = '$100';               # not interpreted
  193.          print "The price is $Price.\n";# interpreted
  194.      Note that you can put curly brackets around the identifier
  195.      to delimit it from following alphanumerics.
  196.      Array literals are denoted by separating individual values
  197.      by commas, and enclosing the list in parentheses.  In a con-
  198.      text not requiring an array value, the value of the array
  199.      literal is the value of the final element, as in the C comma
  200.      operator.  For example,
  201.          @foo = ('cc', '-E', $bar);
  202.      assigns the entire array value to array foo, but
  203.          $foo = ('cc', '-E', $bar);
  204.      assigns the value of variable bar to variable foo.  Array
  205.      lists may be assigned to if and only if each element of the
  206.      list is an lvalue:
  207.          ($a, $b, $c) = (1, 2, 3);
  208.          ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  209.      Numeric literals are specified in any of the usual floating
  210.      point or integer formats.
  211.      There are several other pseudo-literals that you should know
  212.      about.  If a string is enclosed by backticks (grave
  213.      accents), it is interpreted as a command, and the output of
  214.      that command is the value of the pseudo-literal, just like
  215.      in any of the standard shells.  The command is executed each
  216.      time the pseudo-literal is evaluated.  Unlike in csh, no
  217.      interpretation is done on the data--newlines remain new-
  218.      lines.  The status value of the command is returned in $?.
  219.      Evaluating a filehandle in angle brackets yields the next
  220.      line from that file (newline included, so it's never false
  221. Printed 7/26/88               LOCAL                             5
  222. PERL(1)             UNIX Programmer's Manual              PERL(1)
  223.  
  224.      until EOF).  Ordinarily you must assign that value to a
  225.      variable, but there is one situation where in which an
  226.      automatic assignment happens.  If (and only if) the input
  227.      symbol is the only thing inside the conditional of a while
  228.      loop, the value is automatically assigned to the variable
  229.      "$_".  (This may seem like an odd thing to you, but you'll
  230.      use the construct in almost every perl script you write.)
  231.      Anyway, the following lines are equivalent to each other:
  232.          while ($_ = <stdin>) {
  233.          while (<stdin>) {
  234.          for (;<stdin>;) {
  235.      The filehandles stdin, stdout and stderr are predefined.
  236.      Additional filehandles may be created with the open func-
  237.      tion.
  238.      The null filehandle <> is special and can be used to emulate
  239.      the behavior of sed and awk.  Input from <> comes either
  240.      from standard input, or from each file listed on the command
  241.      line.  Here's how it works: the first time <> is evaluated,
  242.      the ARGV array is checked, and if it is null, $ARGV[0] is
  243.      set to '-', which when opened gives you standard input.  The
  244.      ARGV array is then processed as a list of filenames.  The
  245.      loop
  246.           while (<>) {
  247.                ...            # code for each line
  248.           }
  249.      is equivalent to
  250.           unshift(@ARGV, '-') if $#ARGV < $[;
  251.           while ($ARGV = shift) {
  252.                open(ARGV, $ARGV);
  253.                while (<ARGV>) {
  254.                     ...       # code for each line
  255.                }
  256.           }
  257.      except that it isn't as cumbersome to say.  It really does
  258.      shift array ARGV and put the current filename into variable
  259.      ARGV.  It also uses filehandle ARGV internally.  You can
  260.      modify @ARGV before the first <> as long as you leave the
  261.      first filename at the beginning of the array.  Line numbers
  262.      ($.) continue as if the input was one big happy file.
  263.      If you want to set @ARGV to your own list of files, go right
  264.      ahead.  If you want to pass switches into your script, you
  265.      can put a loop on the front like this:
  266. Printed 7/26/88               LOCAL                             6
  267. PERL(1)             UNIX Programmer's Manual              PERL(1)
  268.           while ($_ = $ARGV[0], /^-/) {
  269.                shift;
  270.               last if /^--$/;
  271.                /^-D(.*)/ && ($debug = $1);
  272.                /^-v/ && $verbose++;
  273.                ...       # other switches
  274.           }
  275.           while (<>) {
  276.                ...       # code for each line
  277.           }
  278.      The <> symbol will return FALSE only once.  If you call it
  279.      again after this it will assume you are processing another
  280.      @ARGV list, and if you haven't set @ARGV, will input from
  281.      stdin.
  282.      Syntax
  283.      A perl script consists of a sequence of declarations and
  284.      commands.  The only things that need to be declared in perl
  285.      are report formats and subroutines.  See the sections below
  286.      for more information on those declarations.  All objects are
  287.      assumed to start with a null or 0 value.  The sequence of
  288.      commands is executed just once, unlike in sed and awk
  289.      scripts, where the sequence of commands is executed for each
  290.      input line.  While this means that you must explicitly loop
  291.      over the lines of your input file (or files), it also means
  292.      you have much more control over which files and which lines
  293.      you look at.  (Actually, I'm lying--it is possible to do an
  294.      implicit loop with either the -n or -p switch.)
  295.      A declaration can be put anywhere a command can, but has no
  296.      effect on the execution of the primary sequence of commands.
  297.      Typically all the declarations are put at the beginning or
  298.      the end of the script.
  299.      Perl is, for the most part, a free-form language.  (The only
  300.      exception to this is format declarations, for fairly obvious
  301.      reasons.) Comments are indicated by the # character, and
  302.      extend to the end of the line.  If you attempt to use /* */
  303.      C comments, it will be interpreted either as division or
  304.      pattern matching, depending on the context.  So don't do
  305.      that.
  306.      Compound statements
  307.      In perl, a sequence of commands may be treated as one com-
  308.      mand by enclosing it in curly brackets.  We will call this a
  309.      BLOCK.
  310.      The following compound commands may be used to control flow:
  311. Printed 7/26/88               LOCAL                             7
  312. PERL(1)             UNIX Programmer's Manual              PERL(1)
  313.           if (EXPR) BLOCK
  314.           if (EXPR) BLOCK else BLOCK
  315.           if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  316.           LABEL while (EXPR) BLOCK
  317.           LABEL while (EXPR) BLOCK continue BLOCK
  318.           LABEL for (EXPR; EXPR; EXPR) BLOCK
  319.           LABEL BLOCK continue BLOCK
  320.      Note that, unlike C and Pascal, these are defined in terms
  321.      of BLOCKs, not statements.  This means that the curly brack-
  322.      ets are required--no dangling statements allowed.  If you
  323.      want to write conditionals without curly brackets there are
  324.      several other ways to do it.  The following all do the same
  325.      thing:
  326.          if (!open(foo)) { die "Can't open $foo"; }
  327.          die "Can't open $foo" unless open(foo);
  328.          open(foo) || die "Can't open $foo"; # foo or bust!
  329.          open(foo) ? die "Can't open $foo" : 'hi mom';
  330.                         # a bit exotic, that last one
  331.      The if statement is straightforward.  Since BLOCKs are
  332.      always bounded by curly brackets, there is never any ambi-
  333.      guity about which if an else goes with.  If you use unless
  334.      in place of if, the sense of the test is reversed.
  335.      The while statement executes the block as long as the
  336.      expression is true (does not evaluate to the null string or
  337.      0).  The LABEL is optional, and if present, consists of an
  338.      identifier followed by a colon.  The LABEL identifies the
  339.      loop for the loop control statements next, last and redo
  340.      (see below).  If there is a continue BLOCK, it is always
  341.      executed just before the conditional is about to be
  342.      evaluated again, similarly to the third part of a for loop
  343.      in C.  Thus it can be used to increment a loop variable,
  344.      even when the loop has been continued via the next statement
  345.      (similar to the C "continue" statement).
  346.      If the word while is replaced by the word until, the sense
  347.      of the test is reversed, but the conditional is still tested
  348.      before the first iteration.
  349.      In either the if or the while statement, you may replace
  350.      "(EXPR)" with a BLOCK, and the conditional is true if the
  351.      value of the last command in that block is true.
  352.      The for loop works exactly like the corresponding while
  353.      loop:
  354.  
  355. Printed 7/26/88               LOCAL                             8
  356. PERL(1)             UNIX Programmer's Manual              PERL(1)
  357.           for ($i = 1; $i < 10; $i++) {
  358.                ...
  359.           }
  360.      is the same as
  361.           $i = 1;
  362.           while ($i < 10) {
  363.                ...
  364.           } continue {
  365.                $i++;
  366.           }
  367.      The BLOCK by itself (labeled or not) is equivalent to a loop
  368.      that executes once.  Thus you can use any of the loop con-
  369.      trol statements in it to leave or restart the block.  The
  370.      continue block is optional.  This construct is particularly
  371.      nice for doing case structures.
  372.           foo: {
  373.                if (/abc/) { $abc = 1; last foo; }
  374.                if (/def/) { $def = 1; last foo; }
  375.                if (/xyz/) { $xyz = 1; last foo; }
  376.                $nothing = 1;
  377.           }
  378.      Simple statements
  379.      The only kind of simple statement is an expression evaluated
  380.      for its side effects.  Every expression (simple statement)
  381.      must be terminated with a semicolon.  Note that this is like
  382.      C, but unlike Pascal (and awk).
  383.      Any simple statement may optionally be followed by a single
  384.      modifier, just before the terminating semicolon.  The possi-
  385.      ble modifiers are:
  386.           if EXPR
  387.           unless EXPR
  388.           while EXPR
  389.           until EXPR
  390.      The if and unless modifiers have the expected semantics.
  391.      The while and unless modifiers also have the expected seman-
  392.      tics (conditional evaluated first), except when applied to a
  393.      do-BLOCK command, in which case the block executes once
  394.      before the conditional is evaluated.  This is so that you
  395.      can write loops like:
  396.  
  397. Printed 7/26/88               LOCAL                             9
  398. PERL(1)             UNIX Programmer's Manual              PERL(1)
  399.           do {
  400.                $_ = <stdin>;
  401.                ...
  402.           } until $_ eq ".\n";
  403.      (See the do operator below.  Note also that the loop control
  404.      commands described later will NOT work in this construct,
  405.      since modifiers don't take loop labels.  Sorry.)
  406.      Expressions
  407.  
  408.      Since perl expressions work almost exactly like C expres-
  409.      sions, only the differences will be mentioned here.
  410.      Here's what perl has that C doesn't:
  411.      ()      The null list, used to initialize an array to null.
  412.      .       Concatenation of two strings.
  413.      .=      The corresponding assignment operator.
  414.      eq      String equality (== is numeric equality).  For a
  415.              mnemonic just think of "eq" as a string.  (If you
  416.              are used to the awk behavior of using == for either
  417.              string or numeric equality based on the current form
  418.              of the comparands, beware!  You must be explicit
  419.              here.)
  420.      ne      String inequality (!= is numeric inequality).
  421.      lt      String less than.
  422.      gt      String greater than.
  423.      le      String less than or equal.
  424.      ge      String greater than or equal.
  425.      =~      Certain operations search or modify the string "$_"
  426.              by default.  This operator makes that kind of opera-
  427.              tion work on some other string.  The right argument
  428.              is a search pattern, substitution, or translation.
  429.              The left argument is what is supposed to be
  430.              searched, substituted, or translated instead of the
  431.              default "$_".  The return value indicates the suc-
  432.              cess of the operation.  (If the right argument is an
  433.              expression other than a search pattern, substitu-
  434.              tion, or translation, it is interpreted as a search
  435.              pattern at run time.  This is less efficient than an
  436.              explicit search, since the pattern must be compiled
  437.              every time the expression is evaluated.) The
  438. Printed 7/26/88               LOCAL                            10
  439.  
  440. PERL(1)             UNIX Programmer's Manual              PERL(1)
  441.              precedence of this operator is lower than unary
  442.              minus and autoincrement/decrement, but higher than
  443.              everything else.
  444.      !~      Just like =~ except the return value is negated.
  445.      x       The repetition operator.  Returns a string consist-
  446.              ing of the left operand repeated the number of times
  447.              specified by the right operand.
  448.                   print '-' x 80;          # print row of dashes
  449.                   print '-' x80;      # illegal, x80 is identifier
  450.                   print "\t" x ($tab/8), ' ' x ($tab%8);  # tab over
  451.      x=      The corresponding assignment operator.
  452.      ..      The range operator, which is bistable.  It is false
  453.              as long as its left argument is false.  Once the
  454.              left argument is true, it stays true until the right
  455.              argument is true, AFTER which it becomes false
  456.              again.  (It doesn't become false till the next time
  457.              it's evaluated.  It can become false on the same
  458.              evaluation it became true, but it still returns true
  459.              once.) The .. operator is primarily intended for
  460.              doing line number ranges after the fashion of sed or
  461.              awk.  The precedence is a little lower than || and
  462.              &&.  The value returned is either the null string
  463.              for false, or a sequence number (beginning with 1)
  464.              for true.  The sequence number is reset for each
  465.              range encountered.  The final sequence number in a
  466.              range has the string 'E0' appended to it, which
  467.              doesn't affect its numeric value, but gives you
  468.              something to search for if you want to exclude the
  469.              endpoint.  You can exclude the beginning point by
  470.              waiting for the sequence number to be greater than
  471.              1.  If either argument to .. is static, that argu-
  472.              ment is implicitly compared to the $. variable, the
  473.              current line number.  Examples:
  474.                  if (101 .. 200) { print; }     # print 2nd hundred lines
  475.                  next line if (1 .. /^$/); # skip header lines
  476.                  s/^/> / if (/^$/ .. eof());    # quote body
  477.      -x      A file test.  This unary operator takes one argu-
  478.              ment, a filename, and tests the file to see if some-
  479.              thing is true about it.  It returns 1 for true and
  480.              '' for false.  Precedence is higher than logical and
  481. Printed 7/26/88               LOCAL                            11
  482.  
  483. PERL(1)             UNIX Programmer's Manual              PERL(1)
  484.              relational operators, but lower than arithmetic
  485.              operators.  The operator may be any of:
  486.                   -r   File is readable by effective uid.
  487.                   -w   File is writeable by effective uid.
  488.                   -x   File is executable by effective uid.
  489.                   -o   File is owned by effective uid.
  490.                   -R   File is readable by real uid.
  491.                   -W   File is writeable by real uid.
  492.                   -X   File is executable by real uid.
  493.                   -O   File is owned by real uid.
  494.                   -e   File exists.
  495.                   -z   File has zero size.
  496.                   -s   File has non-zero size.
  497.                   -f   File is a plain file.
  498.                   -d   File is a directory.
  499.                   -l   File is a symbolic link.
  500.  
  501.              Example:
  502.                   while (<>) {
  503.                        chop;
  504.                        next unless -f $_;  # ignore specials
  505.                        ...
  506.                   }
  507.              Note that -s/a/b/ does not do a negated substitu-
  508.              tion.
  509.      Here is what C has that perl doesn't:
  510.      unary &     Address-of operator.
  511.      unary *     Dereference-address operator.
  512.      Like C, perl does a certain amount of expression evaluation
  513.      at compile time, whenever it determines that all of the
  514.      arguments to an operator are static and have no side
  515.      effects.  In particular, string concatenation happens at
  516.      compile time between literals that don't do variable substi-
  517.      tution.  Backslash interpretation also happens at compile
  518.      time.  You can say
  519.           'Now is the time for all' . "\n" .
  520.           'good men to come to.'
  521.      and this all reduces to one string internally.
  522.      Along with the literals and variables mentioned earlier, the
  523.      following operations can serve as terms in an expression:
  524.      /PATTERN/i
  525.              Searches a string for a pattern, and returns true
  526. Printed 7/26/88               LOCAL                            12
  527. PERL(1)             UNIX Programmer's Manual              PERL(1)
  528.              (1) or false ('').  If no string is specified via
  529.              the =~ or !~ operator, the $_ string is searched.
  530.              (The string specified with =~ need not be an
  531.              lvalue--it may be the result of an expression
  532.              evaluation, but remember the =~ binds rather
  533.              tightly.) See also the section on regular expres-
  534.              sions.
  535.              If you prepend an `m' you can use any pair of char-
  536.              acters as delimiters.  This is particularly useful
  537.              for matching Unix path names that contain `/'.  If
  538.              the final delimiter is followed by the optional
  539.              letter `i', the matching is done in a case-
  540.              insensitive manner.
  541.              Examples:
  542.                  open(tty, '/dev/tty');
  543.                  <tty> =~ /^y/i && do foo();    # do foo if desired
  544.  
  545.                  if (/Version: *([0-9.]*)/) { $version = $1; }
  546.                  next if m#^/usr/spool/uucp#;
  547.      ?PATTERN?
  548.              This is just like the /pattern/ search, except that
  549.              it matches only once between calls to the reset
  550.              operator.  This is a useful optimization when you
  551.              only want to see the first occurence of something in
  552.              each of a set of files, for instance.
  553.      chdir EXPR
  554.              Changes the working directory to EXPR, if possible.
  555.              Returns 1 upon success, 0 otherwise.  See example
  556.              under die().
  557.      chmod LIST
  558.              Changes the permissions of a list of files.  The
  559.              first element of the list must be the numerical
  560.              mode.  LIST may be an array, in which case you may
  561.              wish to use the unshift() command to put the mode on
  562.              the front of the array.  Returns the number of files
  563.              successfully changed.  Note: in order to use the
  564.              value you must put the whole thing in parentheses.
  565.                   $cnt = (chmod 0755,'foo','bar');
  566.      chop(VARIABLE)
  567. Printed 7/26/88               LOCAL                            13
  568. PERL(1)             UNIX Programmer's Manual              PERL(1)
  569.  
  570.      chop    Chops off the last character of a string and returns
  571.              it.  It's used primarily to remove the newline from
  572.              the end of an input record, but is much more effi-
  573.              cient than s/\n// because it neither scans nor
  574.              copies the string.  If VARIABLE is omitted, chops
  575.              $_.  Example:
  576.                   while (<>) {
  577.                        chop;     # avoid \n on last field
  578.                        @array = split(/:/);
  579.                        ...
  580.                   }
  581.      chown LIST
  582.              Changes the owner (and group) of a list of files.
  583.              LIST may be an array.  The first two elements of the
  584.              list must be the NUMERICAL uid and gid, in that
  585.              order.  Returns the number of files successfully
  586.              changed.  Note: in order to use the value you must
  587.              put the whole thing in parentheses.
  588.                   $cnt = (chown $uid,$gid,'foo');
  589.              Here's an example of looking up non-numeric uids:
  590.                   print "User: ";
  591.                   $user = <stdin>;
  592.                   chop($user);
  593.                   open(pass,'/etc/passwd') || die "Can't open passwd";
  594.                   while (<pass>) {
  595.                        ($login,$pass,$uid,$gid) = split(/:/);
  596.                        $uid{$login} = $uid;
  597.                        $gid{$login} = $gid;
  598.                   }
  599.                   @ary = ('foo','bar','bie','doll');
  600.                   if ($uid{$user} eq '') {
  601.                        die "$user not in passwd file";
  602.                   }
  603.                   else {
  604.                        unshift(@ary,$uid{$user},$gid{$user});
  605.                        chown @ary;
  606.                   }
  607.      close(FILEHANDLE)
  608.      close FILEHANDLE
  609.              Closes the file or pipe associated with the file
  610.              handle.  You don't have to close FILEHANDLE if you
  611.              are immediately going to do another open on it,
  612.              since open will close it for you.  (See open.)
  613. Printed 7/26/88               LOCAL                            14
  614. PERL(1)             UNIX Programmer's Manual              PERL(1)
  615.              However, an explicit close on an input file resets
  616.              the line counter ($.), while the implicit close done
  617.              by open does not.  Also, closing a pipe will wait
  618.              for the process executing on the pipe to complete,
  619.              in case you want to look at the output of the pipe
  620.              afterwards.  Example:
  621.                   open(output,'|sort >foo');    # pipe to sort
  622.                   ...  # print stuff to output
  623.                   close(output);      # wait for sort to finish
  624.                   open(input,'foo');  # get sort's results
  625.      crypt(PLAINTEXT,SALT)
  626.              Encrypts a string exactly like the crypt() function
  627.              in the C library.  Useful for checking the password
  628.              file for lousy passwords.  Only the guys wearing
  629.              white hats should do this.
  630.      die EXPR
  631.              Prints the value of EXPR to stderr and exits with a
  632.              non-zero status.  Equivalent examples:
  633.                   die "Can't cd to spool." unless chdir '/usr/spool/news';
  634.                   (chdir '/usr/spool/news') || die "Can't cd to spool."
  635.              Note that the parens are necessary above due to pre-
  636.              cedence.  See also exit.
  637.      do BLOCK
  638.              Returns the value of the last command in the
  639.              sequence of commands indicated by BLOCK.  When modi-
  640.              fied by a loop modifier, executes the BLOCK once
  641.              before testing the loop condition.  (On other state-
  642.              ments the loop modifiers test the conditional
  643.              first.)
  644.      do SUBROUTINE (LIST)
  645.              Executes a SUBROUTINE declared by a sub declaration,
  646.              and returns the value of the last expression
  647.              evaluated in SUBROUTINE.  (See the section on sub-
  648.              routines later on.)
  649.      each(ASSOC_ARRAY)
  650.              Returns a 2 element array consisting of the key and
  651.              value for the next value of an associative array, so
  652.              that you can iterate over it.  Entries are returned
  653.              in an apparently random order.  When the array is
  654.              entirely read, a null array is returned (which when
  655.              assigned produces a FALSE (0) value).  The next call
  656.              to each() after that will start iterating again.
  657. Printed 7/26/88               LOCAL                            15
  658. PERL(1)             UNIX Programmer's Manual              PERL(1)
  659.              The iterator can be reset only by reading all the
  660.              elements from the array.  You should not modify the
  661.              array while iterating over it.  The following prints
  662.              out your environment like the printenv program, only
  663.              in a different order:
  664.  
  665.                   while (($key,$value) = each(ENV)) {
  666.                        print "$key=$value\n";
  667.                   }
  668.              See also keys() and values().
  669.      eof(FILEHANDLE)
  670.      eof     Returns 1 if the next read on FILEHANDLE will return
  671.              end of file, or if FILEHANDLE is not open.  If
  672.              (FILEHANDLE) is omitted, the eof status is returned
  673.              for the last file read.  The null filehandle may be
  674.              used to indicate the pseudo file formed of the files
  675.              listed on the command line, i.e. eof() is reasonable
  676.              to use inside a while (<>) loop.  Example:
  677.                   # insert dashes just before last line
  678.                   while (<>) {
  679.                        if (eof()) {
  680.                             print "--------------\n";
  681.                        }
  682.                        print;
  683.                   }
  684.      eval EXPR
  685.              EXPR is parsed and executed as if it were a little
  686.              perl program.  It is executed in the context of the
  687.              current perl program, so that any variable settings,
  688.              subroutine or format definitions remain afterwards.
  689.              The value returned is the value of the last expres-
  690.              sion evaluated, just as with subroutines.  If there
  691.              is a syntax error or runtime error, a null string is
  692.              returned by eval, and $@ is set to the error mes-
  693.              sage.  If there was no error, $@ is null.  If EXPR
  694.              is omitted, evaluates $_.
  695.      exec LIST
  696.              If there is more than one argument in LIST, calls
  697.              execvp() with the arguments in LIST.  If there is
  698.              only one argument, the argument is checked for shell
  699.              metacharacters.  If there are any, the entire argu-
  700.              ment is passed to /bin/sh -c for parsing.  If there
  701.              are none, the argument is split into words and
  702.              passed directly to execvp(), which is more effi-
  703.              cient.  Note: exec (and system) do not flush your
  704. Printed 7/26/88               LOCAL                            16
  705. PERL(1)             UNIX Programmer's Manual              PERL(1)
  706.              output buffer, so you may need to set $| to avoid
  707.              lost output.
  708.      exit EXPR
  709.              Evaluates EXPR and exits immediately with that
  710.              value.  Example:
  711.                   $ans = <stdin>;
  712.                   exit 0 if $ans =~ /^[Xx]/;
  713.              See also die.
  714.      exp(EXPR)
  715.              Returns e to the power of EXPR.
  716.      fork    Does a fork() call.  Returns the child pid to the
  717.              parent process and 0 to the child process.  Note:
  718.              unflushed buffers remain unflushed in both
  719.              processes, which means you may need to set $| to
  720.              avoid duplicate output.
  721.      gmtime(EXPR)
  722.              Converts a time as returned by the time function to
  723.              a 9-element array with the time analyzed for the
  724.              Greenwich timezone.  Typically used as follows:
  725.                  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
  726.                     = gmtime(time);
  727.              All array elements are numeric.
  728.      goto LABEL
  729.              Finds the statement labeled with LABEL and resumes
  730.              execution there.  Currently you may only go to
  731.              statements in the main body of the program that are
  732.              not nested inside a do {} construct.  This statement
  733.              is not implemented very efficiently, and is here
  734.              only to make the sed-to-perl translator easier.  Use
  735.              at your own risk.
  736.      hex(EXPR)
  737.              Returns the decimal value of EXPR interpreted as an
  738.              hex string.  (To interpret strings that might start
  739.              with 0 or 0x see oct().)
  740.      index(STR,SUBSTR)
  741.              Returns the position of SUBSTR in STR, based at 0,
  742.              or whatever you've set the $[ variable to.  If the
  743.              substring is not found, returns one less than the
  744.              base, ordinarily -1.
  745.  
  746. Printed 7/26/88               LOCAL                            17
  747. PERL(1)             UNIX Programmer's Manual              PERL(1)
  748.      int(EXPR)
  749.              Returns the integer portion of EXPR.
  750.      join(EXPR,LIST)
  751.      join(EXPR,ARRAY)
  752.              Joins the separate strings of LIST or ARRAY into a
  753.              single string with fields separated by the value of
  754.              EXPR, and returns the string.  Example:
  755.                  $_ = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  756.  
  757.              See split.
  758.      keys(ASSOC_ARRAY)
  759.              Returns a normal array consisting of all the keys of
  760.              the named associative array.  The keys are returned
  761.              in an apparently random order, but it is the same
  762.              order as either the values() or each() function pro-
  763.              duces (given that the associative array has not been
  764.              modified).  Here is yet another way to print your
  765.              environment:
  766.                   @keys = keys(ENV);
  767.                   @values = values(ENV);
  768.                   while ($#keys >= 0) {
  769.                        print pop(keys),'=',pop(values),"\n";
  770.                   }
  771.      kill LIST
  772.              Sends a signal to a list of processes.  The first
  773.              element of the list must be the (numerical) signal
  774.              to send.  LIST may be an array, in which case you
  775.              may wish to use the unshift command to put the sig-
  776.              nal on the front of the array.  Returns the number
  777.              of processes successfully signaled.  Note: in order
  778.              to use the value you must put the whole thing in
  779.              parentheses:
  780.                   $cnt = (kill 9,$child1,$child2);
  781.              If the signal is negative, kills process groups
  782.              instead of processes.  (On System V, a negative pro-
  783.              cess number will also kill process groups, but
  784.              that's not portable.)
  785.      last LABEL
  786.      last    The last command is like the break statement in C
  787.              (as used in loops); it immediately exits the loop in
  788.              question.  If the LABEL is omitted, the command
  789. Printed 7/26/88               LOCAL                            18
  790.  
  791. PERL(1)             UNIX Programmer's Manual              PERL(1)
  792.              refers to the innermost enclosing loop.  The con-
  793.              tinue block, if any, is not executed:
  794.                   line: while (<stdin>) {
  795.                        last line if /^$/;  # exit when done with header
  796.                        ...
  797.                   }
  798.      localtime(EXPR)
  799.              Converts a time as returned by the time function to
  800.              a 9-element array with the time analyzed for the
  801.              local timezone.  Typically used as follows:
  802.                  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
  803.                     = localtime(time);
  804.              All array elements are numeric.
  805.      log(EXPR)
  806.              Returns logarithm (base e) of EXPR.
  807.      next LABEL
  808.      next    The next command is like the continue statement in
  809.              C; it starts the next iteration of the loop:
  810.                   line: while (<stdin>) {
  811.                        next line if /^#/;  # discard comments
  812.                        ...
  813.                   }
  814.              Note that if there were a continue block on the
  815.              above, it would get executed even on discarded
  816.              lines.  If the LABEL is omitted, the command refers
  817.              to the innermost enclosing loop.
  818.      length(EXPR)
  819.              Returns the length in characters of the value of
  820.              EXPR.
  821.      link(OLDFILE,NEWFILE)
  822.              Creates a new filename linked to the old filename.
  823.              Returns 1 for success, 0 otherwise.
  824.      oct(EXPR)
  825.              Returns the decimal value of EXPR interpreted as an
  826.              octal string.  (If EXPR happens to start off with
  827.              0x, interprets it as a hex string instead.) The fol-
  828.              lowing will handle decimal, octal and hex in the
  829.              standard notation:
  830. Printed 7/26/88               LOCAL                            19
  831.  
  832. PERL(1)             UNIX Programmer's Manual              PERL(1)
  833.                   $val = oct($val) if $val =~ /^0/;
  834.      open(FILEHANDLE,EXPR)
  835.      open(FILEHANDLE)
  836.      open FILEHANDLE
  837.              Opens the file whose filename is given by EXPR, and
  838.              associates it with FILEHANDLE.  If EXPR is omitted,
  839.              the string variable of the same name as the FILEHAN-
  840.              DLE contains the filename.  If the filename begins
  841.              with ">", the file is opened for output.  If the
  842.              filename begins with ">>", the file is opened for
  843.              appending.  If the filename begins with "|", the
  844.              filename is interpreted as a command to which output
  845.              is to be piped, and if the filename ends with a "|",
  846.              the filename is interpreted as command which pipes
  847.              input to us.  (You may not have a command that pipes
  848.              both in and out.) Opening '-' opens stdin and open-
  849.              ing '>-' opens stdout.  Open returns 1 upon success,
  850.              '' otherwise.  Examples:
  851.                  $article = 100;
  852.                  open article || die "Can't find article $article";
  853.                  while (<article>) {...
  854.                  open(log, '>>/usr/spool/news/twitlog');
  855.                  open(article, "caeser <$article |");          # decrypt article
  856.                  open(extract, "|sort >/tmp/Tmp$$");      # $$ is our process#
  857.      ord(EXPR)
  858.              Returns the ascii value of the first character of
  859.              EXPR.
  860.      pop ARRAY
  861.      pop(ARRAY)
  862.              Pops and returns the last value of the array, shor-
  863.              tening the array by 1.
  864.      print FILEHANDLE LIST
  865.      print LIST
  866.      print   Prints a string or comma-separated list of strings.
  867.              If FILEHANDLE is omitted, prints by default to stan-
  868.              dard output (or to the last selected output
  869.              channel--see select()).  If LIST is also omitted,
  870.  
  871. Printed 7/26/88               LOCAL                            20
  872. PERL(1)             UNIX Programmer's Manual              PERL(1)
  873.              prints $_ to stdout.  LIST may also be an array
  874.              value.  To set the default output channel to some-
  875.              thing other than stdout use the select operation.
  876.      printf FILEHANDLE LIST
  877.      printf LIST
  878.              Equivalent to a "print FILEHANDLE sprintf(LIST)".
  879.      push(ARRAY,EXPR)
  880.              Treats ARRAY (@ is optional) as a stack, and pushes
  881.              the value of EXPR onto the end of ARRAY.  The length
  882.              of ARRAY increases by 1.  Has the same effect as
  883.                  $ARRAY[$#ARRAY+1] = EXPR;
  884.              but is more efficient.
  885.      redo LABEL
  886.      redo    The redo command restarts the loop block without
  887.              evaluating the conditional again.  The continue
  888.              block, if any, is not executed.  If the LABEL is
  889.              omitted, the command refers to the innermost enclos-
  890.              ing loop.  This command is normally used by programs
  891.              that want to lie to themselves about what was just
  892.              input:
  893.                   # a simpleminded Pascal comment stripper
  894.                   # (warning: assumes no { or } in strings)
  895.                   line: while (<stdin>) {
  896.                        while (s|({.*}.*){.*}|$1 |) {}
  897.                        s|{.*}| |;
  898.                        if (s|{.*| |) {
  899.                             $front = $_;
  900.                             while (<stdin>) {
  901.                                  if (/}/) {     # end of comment?
  902.                                       s|^|$front{|;
  903.                                       redo line;
  904.                                  }
  905.                             }
  906.                        }
  907.                        print;
  908.                   }
  909.      rename(OLDNAME,NEWNAME)
  910.              Changes the name of a file.  Returns 1 for success,
  911.              0 otherwise.
  912.      reset EXPR
  913.              Generally used in a continue block at the end of a
  914. Printed 7/26/88               LOCAL                            21
  915. PERL(1)             UNIX Programmer's Manual              PERL(1)
  916.              loop to clear variables and reset ?? searches so
  917.              that they work again.  The expression is interpreted
  918.              as a list of single characters (hyphens allowed for
  919.              ranges).  All string variables beginning with one of
  920.              those letters are set to the null string.  If the
  921.              expression is omitted, one-match searches (?pat-
  922.              tern?) are reset to match again.  Always returns 1.
  923.              Examples:
  924.                  reset 'X';      # reset all X variables
  925.                  reset 'a-z';    # reset lower case variables
  926.                  reset;          # just reset ?? searches
  927.  
  928.      s/PATTERN/REPLACEMENT/gi
  929.              Searches a string for a pattern, and if found,
  930.              replaces that pattern with the replacement text and
  931.              returns the number of substitutions made.  Otherwise
  932.              it returns false (0).  The "g" is optional, and if
  933.              present, indicates that all occurences of the pat-
  934.              tern are to be replaced.  The "i" is also optional,
  935.              and if present, indicates that matching is to be
  936.              done in a case-insensitive manner.  Any delimiter
  937.              may replace the slashes; if single quotes are used,
  938.              no interpretation is done on the replacement string.
  939.              If no string is specified via the =~ or !~ operator,
  940.              the $_ string is searched and modified.  (The string
  941.              specified with =~ must be a string variable or array
  942.              element, i.e. an lvalue.) If the pattern contains a
  943.              $ that looks like a variable rather than an end-of-
  944.              string test, the variable will be interpolated into
  945.              the pattern at run-time.  See also the section on
  946.              regular expressions.  Examples:
  947.                  s/\bgreen\b/mauve/g;      # don't change wintergreen
  948.  
  949.                  $path =~ s|/usr/bin|/usr/local/bin|;
  950.                  s/Login: $foo/Login: $bar/; # run-time pattern
  951.                  s/([^ ]*) *([^ ]*)/$2 $1/;     # reverse 1st two fields
  952.              (Note the use of $ instead of \ in the last example.
  953.              See section on regular expressions.)
  954.      seek(FILEHANDLE,POSITION,WHENCE)
  955.              Randomly positions the file pointer for FILEHANDLE,
  956.              just like the fseek() call of stdio.  Returns 1 upon
  957.              success, 0 otherwise.
  958.      select(FILEHANDLE)
  959.              Sets the current default filehandle for output.
  960. Printed 7/26/88               LOCAL                            22
  961.  
  962. PERL(1)             UNIX Programmer's Manual              PERL(1)
  963.              This has two effects: first, a write or a print
  964.              without a filehandle will default to this FILEHAN-
  965.              DLE.  Second, references to variables related to
  966.              output will refer to this output channel.  For exam-
  967.              ple, if you have to set the top of form format for
  968.              more than one output channel, you might do the fol-
  969.              lowing:
  970.                  select(report1);
  971.                  $^ = 'report1_top';
  972.                  select(report2);
  973.                  $^ = 'report2_top';
  974.              Select happens to return TRUE if the file is
  975.              currently open and FALSE otherwise, but this has no
  976.              effect on its operation.
  977.      shift(ARRAY)
  978.      shift ARRAY
  979.      shift   Shifts the first value of the array off and returns
  980.              it, shortening the array by 1 and moving everything
  981.              down.  If ARRAY is omitted, shifts the ARGV array.
  982.              See also unshift(), push() and pop().  Shift() and
  983.              unshift() do the same thing to the left end of an
  984.              array that push() and pop() do to the right end.
  985.      sleep EXPR
  986.      sleep   Causes the script to sleep for EXPR seconds, or for-
  987.              ever if no EXPR.  May be interrupted by sending the
  988.              process a SIGALARM.  Returns the number of seconds
  989.              actually slept.
  990.      split(/PATTERN/,EXPR)
  991.      split(/PATTERN/)
  992.  
  993.      split   Splits a string into an array of strings, and
  994.              returns it.  If EXPR is omitted, splits the $_
  995.              string.  If PATTERN is also omitted, splits on whi-
  996.              tespace (/[ \t\n]+/).  Anything matching PATTERN is
  997.              taken to be a delimiter separating the fields.
  998.              (Note that the delimiter may be longer than one
  999.              character.) Trailing null fields are stripped, which
  1000.              potential users of pop() would do well to remember.
  1001.              A pattern matching the null string (not to be con-
  1002.              fused with a null pattern) will split the value of
  1003.              EXPR into separate characters at each point it
  1004.              matches that way.  For example:
  1005. Printed 7/26/88               LOCAL                            23
  1006.  
  1007. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1008.                   print join(':',split(/ */,'hi there'));
  1009.              produces the output 'h:i:t:h:e:r:e'.
  1010.              The pattern /PATTERN/ may be replaced with an
  1011.              expression to specify patterns that vary at runtime.
  1012.              As a special case, specifying a space (' ') will
  1013.              split on white space just as split with no arguments
  1014.              does, but leading white space does NOT produce a
  1015.              null first field.  Thus, split(' ') can be used to
  1016.              emulate awk's default behavior, whereas split(/ /)
  1017.              will give you as many null initial fields as there
  1018.              are leading spaces.
  1019.              Example:
  1020.                   open(passwd, '/etc/passwd');
  1021.                   while (<passwd>) {
  1022.                        ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  1023.                             = split(/:/);
  1024.                        ...
  1025.                   }
  1026.              (Note that $shell above will still have a newline on
  1027.              it.  See chop().) See also join.
  1028.      sprintf(FORMAT,LIST)
  1029.              Returns a string formatted by the usual printf con-
  1030.              ventions.  The * character is not supported.
  1031.      sqrt(EXPR)
  1032.              Return the square root of EXPR.
  1033.      stat(FILEHANDLE)
  1034.      stat(EXPR)
  1035.              Returns a 13-element array giving the statistics for
  1036.              a file, either the file opened via FILEHANDLE, or
  1037.              named by EXPR.  Typically used as follows:
  1038.                  ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  1039.                     $atime,$mtime,$ctime,$blksize,$blocks)
  1040.                         = stat($filename);
  1041.      substr(EXPR,OFFSET,LEN)
  1042.              Extracts a substring out of EXPR and returns it.
  1043.              First character is at offset 0, or whatever you've
  1044.              set $[ to.
  1045.      system LIST
  1046.              Does exactly the same thing as "exec LIST" except
  1047. Printed 7/26/88               LOCAL                            24
  1048. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1049.  
  1050.              that a fork is done first, and the parent process
  1051.              waits for the child process to complete.  Note that
  1052.              argument processing varies depending on the number
  1053.              of arguments.  The return value is the exit status
  1054.              of the program as returned by the wait() call.  To
  1055.              get the actual exit value divide by 256.  See also
  1056.              exec.
  1057.      symlink(OLDFILE,NEWFILE)
  1058.              Creates a new filename symbolically linked to the
  1059.              old filename.  Returns 1 for success, 0 otherwise.
  1060.              On systems that don't support symbolic links, pro-
  1061.              duces a fatal error.
  1062.      tell(FILEHANDLE)
  1063.      tell    Returns the current file position for FILEHANDLE.
  1064.              If FILEHANDLE is omitted, assumes the file last
  1065.              read.
  1066.      time    Returns the number of seconds since January 1, 1970.
  1067.              Suitable for feeding to gmtime() and localtime().
  1068.      times   Returns a four-element array giving the user and
  1069.              system times, in seconds, for this process and the
  1070.              children of this process.
  1071.                  ($user,$system,$cuser,$csystem) = times;
  1072.      tr/SEARCHLIST/REPLACEMENTLIST/
  1073.      y/SEARCHLIST/REPLACEMENTLIST/
  1074.              Translates all occurences of the characters found in
  1075.              the search list with the corresponding character in
  1076.              the replacement list.  It returns the number of
  1077.              characters replaced.  If no string is specified via
  1078.              the =~ or !~ operator, the $_ string is translated.
  1079.              (The string specified with =~ must be a string vari-
  1080.              able or array element, i.e. an lvalue.) For sed
  1081.              devotees, y is provided as a synonym for tr.  Exam-
  1082.              ples:
  1083.                  $ARGV[1] =~ y/A-Z/a-z/;   # canonicalize to lower case
  1084.  
  1085.                  $cnt = tr/*/*/;           # count the stars in $_
  1086.      umask(EXPR)
  1087.              Sets the umask for the process and returns the old
  1088.              one.
  1089. Printed 7/26/88               LOCAL                            25
  1090. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1091.      unlink LIST
  1092.              Deletes a list of files.  LIST may be an array.
  1093.              Returns the number of files successfully deleted.
  1094.              Note: in order to use the value you must put the
  1095.              whole thing in parentheses:
  1096.                   $cnt = (unlink 'a','b','c');
  1097.      unshift(ARRAY,LIST)
  1098.              Does the opposite of a shift.  Prepends list to the
  1099.              front of the array, and returns the number of ele-
  1100.              ments in the new array.
  1101.                   unshift(ARGV,'-e') unless $ARGV[0] =~ /^-/;
  1102.      values(ASSOC_ARRAY)
  1103.              Returns a normal array consisting of all the values
  1104.              of the named associative array.  The values are
  1105.              returned in an apparently random order, but it is
  1106.              the same order as either the keys() or each() func-
  1107.              tion produces (given that the associative array has
  1108.              not been modified).  See also keys() and each().
  1109.  
  1110.      write(FILEHANDLE)
  1111.      write(EXPR)
  1112.      write() Writes a formatted record (possibly multi-line) to
  1113.              the specified file, using the format associated with
  1114.              that file.  By default the format for a file is the
  1115.              one having the same name is the filehandle, but the
  1116.              format for the current output channel (see select)
  1117.              may be set explicitly by assigning the name of the
  1118.              format to the $~ variable.
  1119.              Top of form processing is handled automatically: if
  1120.              there is insufficient room on the current page for
  1121.              the formatted record, the page is advanced, a spe-
  1122.              cial top-of-page format is used to format the new
  1123.              page header, and then the record is written.  By
  1124.              default the top-of-page format is "top", but it may
  1125.              be set to the format of your choice by assigning the
  1126.              name to the $^ variable.
  1127.              If FILEHANDLE is unspecified, output goes to the
  1128.              current default output channel, which starts out as
  1129.              stdout but may be changed by the select operator.
  1130.              If the FILEHANDLE is an EXPR, then the expression is
  1131.              evaluated and the resulting string is used to look
  1132.              up the name of the FILEHANDLE at run time.  For more
  1133. Printed 7/26/88               LOCAL                            26
  1134. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1135.              on formats, see the section on formats later on.
  1136.      Subroutines
  1137.      A subroutine may be declared as follows:
  1138.          sub NAME BLOCK
  1139.      Any arguments passed to the routine come in as array @_,
  1140.      that is ($_[0], $_[1], ...).  The return value of the sub-
  1141.      routine is the value of the last expression evaluated.
  1142.      There are no local variables--everything is a global vari-
  1143.      able.
  1144.      A subroutine is called using the do operator.  (CAVEAT: For
  1145.      efficiency reasons recursive subroutine calls are not
  1146.      currently supported.  This restriction may go away in the
  1147.      future.  Then again, it may not.)
  1148.      Example:
  1149.           sub MAX {
  1150.                $max = pop(@_);
  1151.                while ($foo = pop(@_)) {
  1152.                     $max = $foo if $max < $foo;
  1153.                }
  1154.                $max;
  1155.           }
  1156.           ...
  1157.           $bestday = do MAX($mon,$tue,$wed,$thu,$fri);
  1158.  
  1159. Printed 7/26/88               LOCAL                            27
  1160. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1161.      Example:
  1162.           # get a line, combining continuation lines
  1163.           #  that start with whitespace
  1164.           sub get_line {
  1165.                $thisline = $lookahead;
  1166.                line: while ($lookahead = <stdin>) {
  1167.                     if ($lookahead =~ /^[ \t]/) {
  1168.                          $thisline .= $lookahead;
  1169.                     }
  1170.                     else {
  1171.                          last line;
  1172.                     }
  1173.                }
  1174.                $thisline;
  1175.           }
  1176.           $lookahead = <stdin>;    # get first line
  1177.           while ($_ = get_line()) {
  1178.                ...
  1179.           }
  1180.      Use array assignment to name your formal arguments:
  1181.           sub maybeset {
  1182.                ($key,$value) = @_;
  1183.                $foo{$key} = $value unless $foo{$key};
  1184.           }
  1185.      Regular Expressions
  1186.      The patterns used in pattern matching are regular expres-
  1187.      sions such as those used by egrep(1).  In addition, \w
  1188.      matches an alphanumeric character and \W a nonalphanumeric.
  1189.      Word boundaries may be matched by \b, and non-boundaries by
  1190.      \B.  The bracketing construct ( ... ) may also be used,
  1191.      $<digit> matches the digit'th substring, where digit can
  1192.      range from 1 to 9.  (You can also use the old standby
  1193.      \<digit> in search patterns, but $<digit> also works in
  1194.      replacement patterns and in the block controlled by the
  1195.      current conditional.) $+ returns whatever the last bracket
  1196.      match matched.  $& returns the entire matched string.  Up to
  1197.      10 alternatives may given in a pattern, separated by |, with
  1198.      the caveat that ( ... | ... ) is illegal.  Examples:
  1199.           s/^([^ ]*) *([^ ]*)/$2 $1/;   # swap first two words
  1200.  
  1201. Printed 7/26/88               LOCAL                            28
  1202. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1203.           if (/Time: (..):(..):(..)/) {
  1204.                $hours = $1;
  1205.                $minutes = $2;
  1206.                $seconds = $3;
  1207.           }
  1208.      By default, the ^ character matches only the beginning of
  1209.      the string, and perl does certain optimizations with the
  1210.      assumption that the string contains only one line.  You may,
  1211.      however, wish to treat a string as a multi-line buffer, such
  1212.      that the ^ will match after any newline within the string.
  1213.      At the cost of a little more overhead, you can do this by
  1214.      setting the variable $* to 1.  Setting it back to 0 makes
  1215.      perl revert to its old behavior.
  1216.      Formats
  1217.      Output record formats for use with the write operator may
  1218.      declared as follows:
  1219.          format NAME =
  1220.          FORMLIST
  1221.          .
  1222.      If name is omitted, format "stdout" is defined.  FORMLIST
  1223.      consists of a sequence of lines, each of which may be of one
  1224.      of three types:
  1225.      1.  A comment.
  1226.      2.  A "picture" line giving the format for one output line.
  1227.      3.  An argument line supplying values to plug into a picture
  1228.          line.
  1229.      Picture lines are printed exactly as they look, except for
  1230.      certain fields that substitute values into the line.  Each
  1231.      picture field starts with either @ or ^.  The @ field (not
  1232.      to be confused with the array marker @) is the normal case;
  1233.      ^ fields are used to do rudimentary multi-line text block
  1234.      filling.  The length of the field is supplied by padding out
  1235.      the field with multiple <, >, or | characters to specify,
  1236.      respectively, left justfication, right justification, or
  1237.      centering.  If any of the values supplied for these fields
  1238.      contains a newline, only the text up to the newline is
  1239.      printed.  The special field @* can be used for printing
  1240.      multi-line values.  It should appear by itself on a line.
  1241.      The values are specified on the following line, in the same
  1242.      order as the picture fields.  They must currently be either
  1243.      string variable names or string literals (or pseudo-
  1244.      literals).  Currently you can separate values with spaces,
  1245. Printed 7/26/88               LOCAL                            29
  1246.  
  1247. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1248.      but commas may be placed between values to prepare for pos-
  1249.      sible future versions in which full expressions are allowed
  1250.      as values.
  1251.      Picture fields that begin with ^ rather than @ are treated
  1252.      specially.  The value supplied must be a string variable
  1253.      name which contains a text string.  Perl puts as much text
  1254.      as it can into the field, and then chops off the front of
  1255.      the string so that the next time the string variable is
  1256.      referenced, more of the text can be printed.  Normally you
  1257.      would use a sequence of fields in a vertical stack to print
  1258.      out a block of text.  If you like, you can end the final
  1259.      field with ..., which will appear in the output if the text
  1260.      was too long to appear in its entirety.
  1261.      Since use of ^ fields can produce variable length records if
  1262.      the text to be formatted is short, you can suppress blank
  1263.      lines by putting the tilde (~) character anywhere in the
  1264.      line.  (Normally you should put it in the front if possi-
  1265.      ble.) The tilde will be translated to a space upon output.
  1266.      Examples:
  1267.      # a report on the /etc/passwd file
  1268.      format top =
  1269.                              Passwd File
  1270.      Name                Login    Office   Uid   Gid Home
  1271.      ------------------------------------------------------------------
  1272.      .
  1273.      format stdout =
  1274.      @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  1275.      $name               $login   $office $uid $gid  $home
  1276.      .
  1277.  
  1278. Printed 7/26/88               LOCAL                            30
  1279.  
  1280. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1281.      # a report from a bug report form
  1282.      format top =
  1283.                              Bug Reports
  1284.      @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  1285.      $system;                      $%;         $date
  1286.      ------------------------------------------------------------------
  1287.      .
  1288.      format stdout =
  1289.      Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  1290.               $subject
  1291.      Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  1292.             $index                        $description
  1293.      Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  1294.                $priority         $date    $description
  1295.      From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  1296.            $from                          $description
  1297.      Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  1298.                   $programmer             $description
  1299.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  1300.                                           $description
  1301.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  1302.                                           $description
  1303.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  1304.                                           $description
  1305.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  1306.                                           $description
  1307.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  1308.                                           $description
  1309.      .
  1310.      It is possible to intermix prints with writes on the same output channel,
  1311.      but you'll have to handle $- (lines left on the page) yourself.
  1312.      If you are printing lots of fields that are usually blank,
  1313.      you should consider using the reset operator between
  1314.      records.  Not only is it more efficient, but it can prevent
  1315.      the bug of adding another field and forgetting to zero it.
  1316.      Predefined Names
  1317.  
  1318.      The following names have special meaning to perl.  I could
  1319.      have used alphabetic symbols for some of these, but I didn't
  1320.      want to take the chance that someone would say reset "a-zA-
  1321.      Z" and wipe them all out.  You'll just have to suffer along
  1322.      with these silly symbols.  Most of them have reasonable
  1323.      mnemonics, or analogues in one of the shells.
  1324.      $_      The default input and pattern-searching space.  The
  1325.              following pairs are equivalent:
  1326.                   while (<>) {...     # only equivalent in while!
  1327.                   while ($_ = <>) {...
  1328. Printed 7/26/88               LOCAL                            31
  1329. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1330.                   /^Subject:/
  1331.                   $_ =~ /^Subject:/
  1332.                   y/a-z/A-Z/
  1333.                   $_ =~ y/a-z/A-Z/
  1334.                   chop
  1335.                   chop($_)
  1336.              (Mnemonic: underline is understood in certain opera-
  1337.              tions.)
  1338.      $.      The current input line number of the last file that
  1339.              was read.  Readonly.  (Mnemonic: many programs use .
  1340.              to mean the current line number.)
  1341.      $/      The input record separator, newline by default.
  1342.              Works like awk's RS variable, including treating
  1343.              blank lines as delimiters if set to the null string.
  1344.              If set to a value longer than one character, only
  1345.              the first character is used.  (Mnemonic: / is used
  1346.              to delimit line boundaries when quoting poetry.)
  1347.      $,      The output field separator for the print operator.
  1348.              Ordinarily the print operator simply prints out the
  1349.              comma separated fields you specify.  In order to get
  1350.              behavior more like awk, set this variable as you
  1351.              would set awk's OFS variable to specify what is
  1352.              printed between fields.  (Mnemonic: what is printed
  1353.              when there is a , in your print statement.)
  1354.      $\      The output record separator for the print operator.
  1355.              Ordinarily the print operator simply prints out the
  1356.              comma separated fields you specify, with no trailing
  1357.              newline or record separator assumed.  In order to
  1358.              get behavior more like awk, set this variable as you
  1359.              would set awk's ORS variable to specify what is
  1360.              printed at the end of the print.  (Mnemonic: you set
  1361.              $\ instead of adding \n at the end of the print.
  1362.              Also, it's just like /, but it's what you get "back"
  1363.              from perl.)
  1364.      $#      The output format for printed numbers.  This vari-
  1365.              able is a half-hearted attempt to emulate awk's OFMT
  1366.              variable.  There are times, however, when awk and
  1367.              perl have differing notions of what is in fact
  1368.              numeric.  Also, the initial value is %.20g rather
  1369.              than %.6g, so you need to set $# explicitly to get
  1370.              awk's value.  (Mnemonic: # is the number sign.)
  1371.      $%      The current page number of the currently selected
  1372.              output channel.  (Mnemonic: % is page number in
  1373. Printed 7/26/88               LOCAL                            32
  1374. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1375.  
  1376.              nroff.)
  1377.      $=      The current page length (printable lines) of the
  1378.              currently selected output channel.  Default is 60.
  1379.              (Mnemonic: = has horizontal lines.)
  1380.      $-      The number of lines left on the page of the
  1381.              currently selected output channel.  (Mnemonic:
  1382.              lines_on_page - lines_printed.)
  1383.      $~      The name of the current report format for the
  1384.              currently selected output channel.  (Mnemonic:
  1385.              brother to $^.)
  1386.      $^      The name of the current top-of-page format for the
  1387.              currently selected output channel.  (Mnemonic:
  1388.              points to top of page.)
  1389.      $|      If set to nonzero, forces a flush after every write
  1390.              or print on the currently selected output channel.
  1391.              Default is 0.  Note that stdout will typically be
  1392.              line buffered if output is to the terminal and block
  1393.              buffered otherwise.  Setting this variable is useful
  1394.              primarily when you are outputting to a pipe, such as
  1395.              when you are running a perl script under rsh and
  1396.              want to see the output as it's happening.
  1397.              (Mnemonic: when you want your pipes to be piping
  1398.              hot.)
  1399.      $$      The process number of the perl running this script.
  1400.              (Mnemonic: same as shells.)
  1401.      $?      The status returned by the last backtick (``) com-
  1402.              mand.  (Mnemonic: same as sh and ksh.)
  1403.      $+      The last bracket matched by the last search pattern.
  1404.              This is useful if you don't know which of a set of
  1405.              alternative patterns matched.  For example:
  1406.                  /Version: (.*)|Revision: (.*)/ && ($rev = $+);
  1407.              (Mnemonic: be positive and forward looking.)
  1408.      $*      Set to 1 to do multiline matching within a string, 0
  1409.              to assume strings contain a single line.  Default is
  1410.              0.  (Mnemonic: * matches multiple things.)
  1411.      $0      Contains the name of the file containing the perl
  1412.              script being executed.  The value should be copied
  1413.              elsewhere before any pattern matching happens, which
  1414.              clobbers $0.  (Mnemonic: same as sh and ksh.)
  1415. Printed 7/26/88               LOCAL                            33
  1416. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1417.      $<digit>
  1418.              Contains the subpattern from the corresponding set
  1419.              of parentheses in the last pattern matched, not
  1420.              counting patterns matched in nested blocks that have
  1421.              been exited already.  (Mnemonic: like \digit.)
  1422.      $[      The index of the first element in an array, and of
  1423.              the first character in a substring.  Default is 0,
  1424.              but you could set it to 1 to make perl behave more
  1425.              like awk (or Fortran) when subscripting and when
  1426.              evaluating the index() and substr() functions.
  1427.              (Mnemonic: [ begins subscripts.)
  1428.      $!      The current value of errno, with all the usual
  1429.              caveats.  (Mnemonic: What just went bang?)
  1430.      $@      The error message from the last eval command.  If
  1431.              null, the last eval parsed and executed correctly.
  1432.              (Mnemonic: Where was the syntax error "at"?)
  1433.      @ARGV   The array ARGV contains the command line arguments
  1434.              intended for the script.  Note that $#ARGV is the
  1435.              generally number of arguments minus one, since
  1436.              $ARGV[0] is the first argument, NOT the command
  1437.              name.  See $0 for the command name.
  1438.  
  1439.      $ENV{expr}
  1440.              The associative array ENV contains your current
  1441.              environment.  Setting a value in ENV changes the
  1442.              environment for child processes.
  1443.      $SIG{expr}
  1444.              The associative array SIG is used to set signal
  1445.              handlers for various signals.  Example:
  1446.                   sub handler {  # 1st argument is signal name
  1447.                        ($sig) = @_;
  1448.                        print "Caught a SIG$sig--shutting down0;
  1449.                        close(log);
  1450.                        exit(0);
  1451.                   }
  1452.                   $SIG{'INT'} = 'handler';
  1453.                   $SIG{'QUIT'} = 'handler';
  1454.                   ...
  1455.                   $SIG{'INT'} = 'DEFAULT'; # restore default action
  1456.                   $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
  1457.  
  1458. ENVIRONMENT
  1459.      Perl currently uses no environment variables, except to make
  1460.      them available to the script being executed, and to child
  1461. Printed 7/26/88               LOCAL                            34
  1462. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1463.      processes.  However, scripts running setuid would do well to
  1464.      execute the following lines before doing anything else, just
  1465.      to keep people honest:
  1466.          $ENV{'PATH'} = '/bin:/usr/bin';    # or whatever you need
  1467.          $ENV{'SHELL'} = '/bin/sh' if $ENV{'SHELL'};
  1468.          $ENV{'IFS'} = '' if $ENV{'IFS'};
  1469. AUTHOR
  1470.      Larry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
  1471. FILES
  1472.      /tmp/perl-eXXXXXX   temporary file for -e commands.
  1473. SEE ALSO
  1474.      a2p  awk to perl translator
  1475.      s2p  sed to perl translator
  1476.      perldb    interactive perl debugger
  1477. DIAGNOSTICS
  1478.      Compilation errors will tell you the line number of the
  1479.      error, with an indication of the next token or token type
  1480.      that was to be examined.  (In the case of a script passed to
  1481.      perl via -e switches, each -e is counted as one line.)
  1482. TRAPS
  1483.      Accustomed awk users should take special note of the follow-
  1484.      ing:
  1485.      *   Semicolons are required after all simple statements in
  1486.          perl.  Newline is not a statement delimiter.
  1487.      *   Curly brackets are required on ifs and whiles.
  1488.      *   Variables begin with $ or @ in perl.
  1489.      *   Arrays index from 0 unless you set $[.  Likewise string
  1490.          positions in substr() and index().
  1491.      *   You have to decide whether your array has numeric or
  1492.          string indices.
  1493.      *   You have to decide whether you want to use string or
  1494.          numeric comparisons.
  1495.      *   Reading an input line does not split it for you.  You
  1496.          get to split it yourself to an array.  And split has
  1497.          different arguments.
  1498.      *   The current input line is normally in $_, not $0.  It
  1499.          generally does not have the newline stripped.  ($0 is
  1500. Printed 7/26/88               LOCAL                            35
  1501. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1502.          initially the name of the program executed, then the
  1503.          last matched string.)
  1504.      *   The current filename is $ARGV, not $FILENAME.  NR, RS,
  1505.          ORS, OFS, and OFMT have equivalents with other symbols.
  1506.          FS doesn't have an equivalent, since you have to be
  1507.          explicit about split statements.
  1508.      *   $<digit> does not refer to fields--it refers to sub-
  1509.          strings matched by the last match pattern.
  1510.      *   The print statement does not add field and record
  1511.          separators unless you set $, and $\.
  1512.      *   You must open your files before you print to them.
  1513.      *   The range operator is "..", not comma.  (The comma
  1514.          operator works as in C.)
  1515.      *   The match operator is "=~", not "~".  ("~" is the one's
  1516.          complement operator.)
  1517.      *   The concatenation operator is ".", not the null string.
  1518.          (Using the null string would render "/pat/ /pat/"
  1519.          unparseable, since the third slash would be interpreted
  1520.          as a division operator--the tokener is in fact slightly
  1521.          context sensitive for operators like /, ?, and <.  And
  1522.          in fact, . itself can be the beginning of a number.)
  1523.      *   The \nnn construct in patterns must be given as [\nnn]
  1524.          to avoid interpretation as a backreference.
  1525.  
  1526.      *   Next, exit, and continue work differently.
  1527.      *   When in doubt, run the awk construct through a2p and see
  1528.          what it gives you.
  1529.      Cerebral C programmers should take note of the following:
  1530.      *   Curly brackets are required on ifs and whiles.
  1531.      *   You should use "elsif" rather than "else if"
  1532.      *   Break and continue become last and next, respectively.
  1533.      *   There's no switch statement.
  1534.      *   Variables begin with $ or @ in perl.
  1535.      *   Printf does not implement *.
  1536.  
  1537. Printed 7/26/88               LOCAL                            36
  1538. PERL(1)             UNIX Programmer's Manual              PERL(1)
  1539.      *   Comments begin with #, not /*.
  1540.      *   You can't take the address of anything.
  1541.      *   Subroutines are not reentrant.
  1542.      *   ARGV must be capitalized.
  1543.      *   The "system" calls link, unlink, rename, etc. return 1
  1544.          for success, not 0.
  1545.      *   Signal handlers deal with signal names, not numbers.
  1546.      Seasoned sed programmers should take note of the following:
  1547.      *   Backreferences in substitutions use $ rather than \.
  1548.      *   The pattern matching metacharacters (, ), and | do not
  1549.          have backslashes in front.
  1550. BUGS
  1551.      You can't currently dereference array elements inside a
  1552.      double-quoted string.  You must assign them to a temporary
  1553.      and interpolate that.
  1554.      Associative arrays really ought to be first class objects.
  1555.      Recursive subroutines are not currently supported, due to
  1556.      the way temporary values are stored in the syntax tree.
  1557.      Arrays ought to be passable to subroutines just as strings
  1558.      are.
  1559.      The array literal consisting of one element is currently
  1560.      misinterpreted, i.e.
  1561.           @array = (123);
  1562.      doesn't work right.
  1563.      Perl actually stands for Pathologically Eclectic Rubbish
  1564.      Lister, but don't tell anyone I said that.
  1565. Printed 7/26/88               LOCAL                            37
  1566.