home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / unix / doc / perl.man < prev    next >
Text File  |  1993-06-13  |  267KB  |  6,997 lines

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