home *** CD-ROM | disk | FTP | other *** search
/ Il CD di internet / CD.iso / SOURCE / D / PERL / PERL-4.036 / PERL-4 / perl-4.036 / Info / perl.info-5 < prev    next >
Encoding:
GNU Info File  |  1994-07-08  |  47.2 KB  |  1,217 lines

  1. This is Info file perl.info, produced by Makeinfo-1.55 from the input
  2. file perltexi.
  3.  
  4.    This file documents perl, Practical Extraction and Report Language,
  5. and was originally based on Larry Wall's unix-style man page for perl.
  6.  
  7.    GNU Texinfo version adapted by Jeff Kellem
  8. <composer@Beyond.Dreams.ORG>.
  9.  
  10.    Copyright (C) 1989, 1990, 1991, 1992, 1993 Larry Wall Texinfo
  11. version Copyright (C) 1990, 1991, 1993 Jeff Kellem
  12.  
  13.    Permission is granted to make and distribute verbatim copies of this
  14. manual provided the copyright notice and this permission notice are
  15. preserved on all copies.
  16.  
  17.    Permission is granted to copy and distribute modified versions of
  18. this manual under the conditions for verbatim copying, provided also
  19. that the sections entitled "GNU General Public License" and "Conditions
  20. for Using Perl" are included exactly as in the original, and provided
  21. that the entire resulting derived work is distributed under the terms
  22. of a permission notice identical to this one.
  23.  
  24.    Permission is granted to copy and distribute translations of this
  25. manual into another language, under the above conditions for modified
  26. versions, except that the section entitled "GNU General Public License"
  27. and this permission notice may be included in translations approved by
  28. the Free Software Foundation instead of in the original English.
  29.  
  30. 
  31. File: perl.info,  Node: Miscellaneous Functions,  Prev: Variable Functions,  Up: Commands
  32.  
  33. Miscellaneous Functions
  34. =======================
  35.  
  36. dump LABEL
  37. dump
  38.      This causes an immediate core dump.  Primarily this is so that you
  39.      can use the `undump' program to turn your core dump into an
  40.      executable binary after having initialized all your variables at
  41.      the beginning of the program.  When the new binary is executed it
  42.      will begin by executing a `goto LABEL' (with all the restrictions
  43.      that `goto' suffers).  Think of it as a `goto' with an intervening
  44.      core dump and reincarnation.  If LABEL is omitted, restarts the
  45.      program from the top.  *WARNING*: any files opened at the time of
  46.      the dump will *NOT* be open any more when the program is
  47.      reincarnated, with possible resulting confusion on the part of
  48.      perl.  See also `-u'.
  49.  
  50.      Example:
  51.  
  52.           #!/usr/bin/perl
  53.               require 'getopt.pl';
  54.               require 'stat.pl';
  55.               %days = (
  56.                   'Sun',1,
  57.                   'Mon',2,
  58.                   'Tue',3,
  59.                   'Wed',4,
  60.                   'Thu',5,
  61.                   'Fri',6,
  62.                   'Sat',7);
  63.           
  64.               dump QUICKSTART if $ARGV[0] eq '-d';
  65.           
  66.           QUICKSTART:
  67.               do Getopt('f');
  68.               ...
  69.  
  70. eval(EXPR)
  71. eval EXPR
  72. eval BLOCK
  73. eval
  74.      EXPR is parsed and executed as if it were a little *perl* program.
  75.      It is executed in the context of the current *perl* program, so
  76.      that any variable settings, subroutine or format definitions
  77.      remain afterwards.  The value returned is the value of the last
  78.      expression evaluated, just as with subroutines.  If there is a
  79.      syntax error or runtime error, or a `die' statement is executed, an
  80.      undefined value is returned by `eval', and `$@' is set to the
  81.      error message.  If there was no error, `$@' is guaranteed to be a
  82.      null string.  If EXPR is omitted, evaluates `$_'.  The final
  83.      semicolon, if any, may be omitted from the expression.
  84.  
  85.      Note that, since `eval' traps otherwise-fatal errors, it is useful
  86.      for determining whether a particular feature (such as `dbmopen' or
  87.      `symlink') is implemented.  If is also *Perl*'s exception trapping
  88.      mechanism, where the `die' operator is used to raise exceptions.
  89.  
  90.      If the code to be executed doesn't vary, you may use the `eval
  91.      BLOCK' form to trap run-time errors without incurring the penalty
  92.      of recompiling each time.  The error, if any, is still returned in
  93.      `$@'.  Evaluating a single-quoted string (as EXPR) has the same
  94.      effect, except that the `eval EXPR' form reports syntax errors at
  95.      run time via `$@', whereas the `eval BLOCK' form reports syntax
  96.      errors at compile time.  The `eval EXPR' form is optimized to
  97.      `eval BLOCK' the first time it succeeds.  (Since the replacement
  98.      side of a substitution is considered a single-quoted string when
  99.      you use the `e' modifier, the same optimization occurs there.)
  100.      Examples:
  101.  
  102.           # make divide-by-zero non-fatal
  103.           eval { $answer = $a / $b; }; warn $@ if $@;
  104.           
  105.           # optimized to same thing after first use
  106.           eval '$answer = $a / $b'; warn $@ if $@;
  107.           
  108.           # a compile-time error
  109.           eval { $answer = };
  110.           
  111.           # a run-time error
  112.           eval '$answer =';       # sets $@
  113.  
  114. ord(EXPR)
  115. ord EXPR
  116. ord
  117.      Returns the numeric ascii value of the first character of EXPR.
  118.      If EXPR is omitted, uses `$_'.
  119.  
  120. q/STRING/
  121. qq/STRING/
  122. qx/STRING/
  123.      These are not really functions, but simply syntactic sugar to let
  124.      you avoid putting too many backslashes into quoted strings.  The
  125.      `q' operator is a generalized single quote, and the `qq' operator a
  126.      generalized double quote.  The `qx' operator is a generalized
  127.      backquote.  Any non-alphanumeric delimiter can be used in place of
  128.      `/', including newline.  If the delimiter is an opening bracket or
  129.      parenthesis, the final delimiter will be the corresponding closing
  130.      bracket or parenthesis.  (Embedded occurrences of the closing
  131.      bracket need to be backslashed as usual.)  Examples:
  132.  
  133.           $foo = q!I said, "You said, 'She said it.'"!;
  134.           $bar = q('This is it.');
  135.           $today = qx{ date };
  136.           $_ .= qq
  137.           *** The previous line contains the naughty word "$&".\n
  138.                   if /(ibm|apple|awk)/;      # :-)
  139.  
  140. rand(EXPR)
  141. rand EXPR
  142. rand
  143.      Returns a random fractional number between 0 and the value of
  144.      EXPR.  (EXPR should be positive.)  If EXPR is omitted, returns a
  145.      value between 0 and 1.  See also `srand()'.
  146.  
  147. srand(EXPR)
  148. srand EXPR
  149. srand
  150.      Sets the random number seed for the `rand' operator.  If EXPR is
  151.      omitted, does `srand(time)'.
  152.  
  153. sprintf(FORMAT,LIST)
  154.      Returns a string formatted by the usual `printf' conventions.  The
  155.      `*' character is not supported.
  156.  
  157. vec(EXPR,OFFSET,BITS)
  158.      Treats a string as a vector of unsigned integers, and returns the
  159.      value of the bitfield specified.  May also be assigned to.  BITS
  160.      must be a power of two from 1 to 32.
  161.  
  162.      Vectors created with `vec()' can also be manipulated with the
  163.      logical operators `|', `&' and `^', which will assume a bit vector
  164.      operation is desired when both operands are strings.  This
  165.      interpretation is not enabled unless there is at least one `vec()'
  166.      in your program, to protect older programs.
  167.  
  168.      To transform a bit vector into a string or array of 0's and 1's,
  169.      use these:
  170.  
  171.           $bits = unpack("b*", $vector);
  172.           @bits = split(//, unpack("b*", $vector));
  173.  
  174.      If you know the exact length in bits, it can be used in place of
  175.      the *.
  176.  
  177. 
  178. File: perl.info,  Node: Precedence,  Next: Subroutines,  Prev: Commands,  Up: Top
  179.  
  180. Precedence
  181. **********
  182.  
  183.    *Perl* operators have the following associativity and precedence:
  184.  
  185.      nonassoc   print printf exec system sort reverse
  186.                      chmod chown kill unlink utime die return
  187.      left       ,
  188.      right      = += \-= *= etc.
  189.      right      ?:
  190.      nonassoc   ..
  191.      left       ||
  192.      left       &&
  193.      left       | ^
  194.      left       &
  195.      nonassoc   == != <=> eq ne cmp
  196.      nonassoc   < > <= >= lt gt le ge
  197.      nonassoc   chdir exit eval reset sleep rand umask
  198.      nonassoc   -r -w -x etc.
  199.      left       << >>
  200.      left       + - .
  201.      left       * / % x
  202.      left       =~ !~
  203.      right      ! ~ and unary minus
  204.      right      **
  205.      nonassoc   ++ --
  206.      left       `('
  207.  
  208.    As mentioned earlier, if any list operator (`print', etc.) or any
  209. unary operator (`chdir', etc.)  is followed by a left parenthesis as
  210. the next token on the same line, the operator and arguments within
  211. parentheses are taken to be of highest precedence, just like a normal
  212. function call.  Examples:
  213.  
  214.      chdir $foo || die;              # (chdir $foo) || die
  215.      chdir($foo) || die;             # (chdir $foo) || die
  216.      chdir ($foo) || die;            # (chdir $foo) || die
  217.      chdir +($foo) || die;           # (chdir $foo) || die
  218.  
  219.    but, because `*' is higher precedence than `||':
  220.  
  221.      chdir $foo * 20;                # chdir ($foo * 20)
  222.      chdir($foo) * 20;               # (chdir $foo) * 20
  223.      chdir ($foo) * 20;              # (chdir $foo) * 20
  224.      chdir +($foo) * 20;             # chdir ($foo * 20)
  225.      
  226.      rand 10 * 20;                   # rand (10 * 20)
  227.      rand(10) * 20;                  # (rand 10) * 20
  228.      rand (10) * 20;                 # (rand 10) * 20
  229.      rand +(10) * 20;                # rand (10 * 20)
  230.  
  231.    In the absence of parentheses, the precedence of list operators such
  232. as `print', `sort' or `chmod' is either very high or very low depending
  233. on whether you look at the left side of operator or the right side of
  234. it.  For example, in
  235.  
  236.      @ary = (1, 3, sort 4, 2);
  237.      print @ary;            # prints 1324
  238.  
  239.    the commas on the right of the sort are evaluated before the sort,
  240. but the commas on the left are evaluated after.  In other words, list
  241. operators tend to gobble up all the arguments that follow them, and then
  242. act like a simple term with regard to the preceding expression.  Note
  243. that you have to be careful with parens:
  244.  
  245.      # These evaluate exit before doing the print:
  246.      print($foo, exit);      # Obviously not what you want.
  247.      print $foo, exit;       # Nor is this.
  248.      
  249.      # These do the print before evaluating exit:
  250.      (print $foo), exit;     # This is what you want.
  251.      print($foo), exit;      # Or this.
  252.      print ($foo), exit;     # Or even this.
  253.  
  254.    Also note that
  255.  
  256.      print ($foo & 255) + 1, "\n";
  257.  
  258.    probably doesn't do what you expect at first glance.
  259.  
  260. 
  261. File: perl.info,  Node: Subroutines,  Next: Passing By Reference,  Prev: Precedence,  Up: Top
  262.  
  263. Subroutines
  264. ***********
  265.  
  266.    A subroutine may be declared as follows:
  267.  
  268.      sub NAME BLOCK
  269.  
  270.    Any arguments passed to the routine come in as array `@_', that is
  271. `($_[0], $_[1], ...)'.  The array `@_' is a local array, but its values
  272. are references to the actual scalar parameters.  The return value of
  273. the subroutine is the value of the last expression evaluated, and can
  274. be either an array value or a scalar value.  Alternately, a return
  275. statement may be used to specify the returned value and exit the
  276. subroutine.  To create local variables see the `local' operator.
  277.  
  278.    A subroutine is called using the `do' operator or the `&' operator.
  279.  
  280.    Example:
  281.  
  282.      sub MAX {
  283.              local($max) = pop(@_);
  284.              foreach $foo (@_) {
  285.                      $max = $foo if $max < $foo;
  286.              }
  287.              $max;
  288.      }
  289.      
  290.      ...
  291.      $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  292.  
  293.    Example:
  294.  
  295.      # get a line, combining continuation lines
  296.      #  that start with whitespace
  297.      sub get_line {
  298.              $thisline = $lookahead;
  299.              line: while ($lookahead = <STDIN>) {
  300.                      if ($lookahead =~ /^[ \t]/) {
  301.                              $thisline .= $lookahead;
  302.                      }
  303.                      else {
  304.                              last line;
  305.                      }
  306.              }
  307.              $thisline;
  308.      }
  309.      
  310.      $lookahead = <STDIN>;   # get first line
  311.      while ($_ = do get_line()) {
  312.              ...
  313.      }
  314.  
  315.    Use array assignment to a local list to name your formal arguments:
  316.  
  317.      sub maybeset {
  318.              local($key, $value) = @_;
  319.              $foo{$key} = $value unless $foo{$key};
  320.      }
  321.  
  322.    This also has the effect of turning call-by-reference into
  323. call-by-value, since the assignment copies the values.
  324.  
  325.    Subroutines may be called recursively.  If a subroutine is called
  326. using the `&' form, the argument list is optional.  If omitted, no `@_'
  327. array is set up for the subroutine; the `@_' array at the time of the
  328. call is visible to subroutine instead.
  329.  
  330.      do foo(1,2,3);          # pass three arguments
  331.      &foo(1,2,3);            # the same
  332.      
  333.      do foo();               # pass a null list
  334.      &foo();                 # the same
  335.      &foo;                   # pass no arguments--more efficient
  336.  
  337. 
  338. File: perl.info,  Node: Passing By Reference,  Next: Regular Expressions,  Prev: Subroutines,  Up: Top
  339.  
  340. Passing By Reference
  341. ********************
  342.  
  343.    Sometimes you don't want to pass the value of an array to a
  344. subroutine but rather the name of it, so that the subroutine can modify
  345. the global copy of it rather than working with a local copy.  In perl
  346. you can refer to all the objects of a particular name by prefixing the
  347. name with a star: `*foo'.  When evaluated, it produces a scalar value
  348. that represents all the objects of that name, including any filehandle,
  349. format or subroutine.  When assigned to within a `local()' operation,
  350. it causes the name mentioned to refer to whatever `*' value was
  351. assigned to it.  Example:
  352.  
  353.      sub doubleary {
  354.          local(*someary) = @_;
  355.          foreach $elem (@someary) {
  356.              $elem *= 2;
  357.          }
  358.      }
  359.      do doubleary(*foo);
  360.      do doubleary(*bar);
  361.  
  362.    Assignment to `*name' is currently recommended only inside a
  363. `local()'.  You can actually assign to `*name' anywhere, but the
  364. previous referent of `*name' may be stranded forever.  This may or may
  365. not bother you.
  366.  
  367.    Note that scalars are already passed by reference, so you can modify
  368. scalar arguments without using this mechanism by referring explicitly to
  369. the `$_[nnn]' in question.  You can modify all the elements of an array
  370. by passing all the elements as scalars, but you have to use the `*'
  371. mechanism to `push', `pop' or change the size of an array.  The `*'
  372. mechanism will probably be more efficient in any case.
  373.  
  374.    Since a `*name' value contains unprintable binary data, if it is
  375. used as an argument in a `print', or as a `%s' argument in a `printf'
  376. or `sprintf', it then has the value `*name', just so it prints out
  377. pretty.
  378.  
  379.    Even if you don't want to modify an array, this mechanism is useful
  380. for passing multiple arrays in a single LIST, since normally the LIST
  381. mechanism will merge all the array values so that you can't extract out
  382. the individual arrays.
  383.  
  384. 
  385. File: perl.info,  Node: Regular Expressions,  Next: Formats,  Prev: Passing By Reference,  Up: Top
  386.  
  387. Regular Expressions
  388. *******************
  389.  
  390.    The patterns used in pattern matching are regular expressions such as
  391. those supplied in the Version 8 regexp routines.  (In fact, the routines
  392. are derived from Henry Spencer's freely redistributable reimplementation
  393. of the V8 routines.)  In addition, `\w' matches an alphanumeric
  394. character (including `_') and `\W' a nonalphanumeric.  Word boundaries
  395. may be matched by `\b', and non-boundaries by `\B'.  A whitespace
  396. character is matched by `\s', non-whitespace by `\S'.  A numeric
  397. character is matched by `\d', non-numeric by `\D'.  You may use `\w',
  398. `\s' and `\d' within character classes.  Also, `\n', `\r', `\f', `\t'
  399. and `\NNN' have their normal interpretations.  Within character classes
  400. `\b' represents backspace rather than a word boundary.  Alternatives
  401. may be separated by `|'.  The bracketing construct `(...)' may also be
  402. used, in which case `\<digit>' matches the digit'th substring.
  403. (Outside of the pattern, always use `$' instead of `\' in front of the
  404. digit.  The scope of `$<digit>' (and `$`', `$&' and `$'') extends to
  405. the end of the enclosing BLOCK or eval string, or to the next pattern
  406. match with subexpressions.  The `\<digit>' notation sometimes works
  407. outside the current pattern, but should not be relied upon.)  You may
  408. have as many parentheses as you wish.  If you have more than 9
  409. substrings, the variables `$10', `$11', ... refer to the corresponding
  410. substring.  Within the pattern, `\10', `\11', etc. refer back to
  411. substrings if there have been at least that many left parens before the
  412. backreference.  Otherwise (for backward compatibilty) `\10' is the same
  413. as `\010', a backspace, and `\11' the same as `\011', a tab.  And so
  414. on.  (`\1' through `\9' are always backreferences.)
  415.  
  416.    `$+' returns whatever the last bracket match matched.  `$&' returns
  417. the entire matched string.  (`$0' used to return the same thing, but
  418. not any more.)  `$`' returns everything before the matched string.
  419. `$'' returns everything after the matched string.  Examples:
  420.  
  421.      s/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words
  422.      
  423.      if (/Time: (..):(..):(..)/) {
  424.              $hours = $1;
  425.              $minutes = $2;
  426.              $seconds = $3;
  427.      }
  428.  
  429.    By default, the `^' character is only guaranteed to match at the
  430. beginning of the string, the `$' character only at the end (or before
  431. the newline at the end) and *perl* does certain optimizations with the
  432. assumption that the string contains only one line.  The behavior of `^'
  433. and `$' on embedded newlines will be inconsistent.  You may, however,
  434. wish to treat a string as a multi-line buffer, such that the `^' will
  435. match after any newline within the string, and `$' will match before
  436. any newline.  At the cost of a little more overhead, you can do this by
  437. setting the variable `$*' to 1.  Setting it back to 0 makes *perl*
  438. revert to its old behavior.
  439.  
  440.    To facilitate multi-line substitutions, the `.' character never
  441. matches a newline (even when `$*' is 0).  In particular, the following
  442. leaves a newline on the `$_' string:
  443.  
  444.      $_ = <STDIN>;
  445.      s/.*(some_string).*/$1/;
  446.  
  447.    If the newline is unwanted, try one of
  448.  
  449.      s/.*(some_string).*\n/$1/;
  450.      s/.*(some_string)[^\000]*/$1/;
  451.      s/.*(some_string)(.|\n)*/$1/;
  452.      chop; s/.*(some_string).*/$1/;
  453.      /(some_string)/ && ($_ = $1);
  454.  
  455.    Any item of a regular expression may be followed with digits in curly
  456. brackets of the form `{N,M}', where N gives the minimum number of times
  457. to match the item and M gives the maximum.  The form `{n}' is
  458. equivalent to `{n,n}' and matches exactly N times.  The form `{n,}'
  459. matches N or more times.  (If a curly bracket occurs in any other
  460. context, it is treated as a regular character.)  The `*' modifier is
  461. equivalent to `{0,}', the `+' modifier to `{1,}' and the `?' modifier to
  462. `{0,1}'.  There is no limit to the size of N or M, but large numbers
  463. will chew up more memory.
  464.  
  465.    You will note that all backslashed metacharacters in *perl* are
  466. alphanumeric, such as `\b', `\w', `\n'.  Unlike some other regular
  467. expression languages, there are no backslashed symbols that aren't
  468. alphanumeric.  So anything that looks like `\\', `\(', `\)', `\<',
  469. `\>', `\{', or `\}' is always interpreted as a literal character, not a
  470. metacharacter.  This makes it simple to quote a string that you want to
  471. use for a pattern but that you are afraid might contain metacharacters.
  472. Simply quote all the non-alphanumeric characters:
  473.  
  474.      $pattern =~ s/(\W)/\\$1/g;
  475.  
  476. 
  477. File: perl.info,  Node: Formats,  Next: Interprocess Communication,  Prev: Regular Expressions,  Up: Top
  478.  
  479. Formats
  480. *******
  481.  
  482.    Output record formats for use with the `write' operator may declared
  483. as follows:
  484.  
  485.      format NAME =
  486.      FORMLIST
  487.      .
  488.  
  489.    If name is omitted, format `STDOUT' is defined.  FORMLIST consists
  490. of a sequence of lines, each of which may be of one of three types:
  491.  
  492.   1. A comment.
  493.  
  494.   2. A "picture" line giving the format for one output line.
  495.  
  496.   3. An argument line supplying values to plug into a picture line.
  497.  
  498.    Picture lines are printed exactly as they look, except for certain
  499. fields that substitute values into the line.  Each picture field starts
  500. with either `@' or `^'.  The `@' field (not to be confused with the
  501. array marker `@') is the normal case; `^' fields are used to do
  502. rudimentary multi-line text block filling.  The length of the field is
  503. supplied by padding out the field with multiple `<', `>', or `|'
  504. characters to specify, respectively, left justification, right
  505. justification, or centering.  As an alternate form of right
  506. justification, you may also use `#' characters (with an optional `.')
  507. to specify a numeric field.  (Use of `^' instead of `@' causes the
  508. field to be blanked if undefined.)  If any of the values supplied for
  509. these fields contains a newline, only the text up to the newline is
  510. printed.  The special field `@*' can be used for printing multi-line
  511. values.  It should appear by itself on a line.
  512.  
  513.    The values are specified on the following line, in the same order as
  514. the picture fields.  The values should be separated by commas.
  515.  
  516.    Picture fields that begin with `^' rather than `@' are treated
  517. specially.  The value supplied must be a scalar variable name which
  518. contains a text string.  *Perl* puts as much text as it can into the
  519. field, and then chops off the front of the string so that the next time
  520. the variable is referenced, more of the text can be printed.  Normally
  521. you would use a sequence of fields in a vertical stack to print out a
  522. block of text.  If you like, you can end the final field with `...',
  523. which will appear in the output if the text was too long to appear in
  524. its entirety.  You can change which characters are legal to break on by
  525. changing the variable `$:' to a list of the desired characters.
  526.  
  527.    Since use of `^' fields can produce variable length records if the
  528. text to be formatted is short, you can suppress blank lines by putting
  529. the tilde (`~') character anywhere in the line.  (Normally you should
  530. put it in the front if possible, for visibility.)  The tilde will be
  531. translated to a space upon output.  If you put a second tilde
  532. contiguous to the first, the line will be repeated until all the fields
  533. on the line are exhausted.  (If you use a field of the `@' variety, the
  534. expression you supply had better not give the same value every time
  535. forever!)
  536.  
  537.    Examples:
  538.  
  539.      # a report on the /etc/passwd file
  540.      format STDOUT_TOP =
  541.                              Passwd File
  542.      Name                Login    Office   Uid   Gid Home
  543.      ------------------------------------------------------------------
  544.      .
  545.      format STDOUT =
  546.      @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  547.      $name,              $login,  $office,$uid,$gid, $home
  548.      .
  549.      
  550.      # a report from a bug report form
  551.      format STDOUT_TOP =
  552.                              Bug Reports
  553.      @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  554.      $system,                      $%,         $date
  555.      ------------------------------------------------------------------
  556.      .
  557.      format STDOUT =
  558.      Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  559.               $subject
  560.      Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  561.             $index,                       $description
  562.      Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  563.                $priority,        $date,   $description
  564.      From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  565.            $from,                         $description
  566.      Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  567.                   $programmer,            $description
  568.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  569.                                           $description
  570.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  571.                                           $description
  572.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  573.                                           $description
  574.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  575.                                           $description
  576.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  577.                                           $description
  578.      .
  579.  
  580.    It is possible to intermix `print's with `write's on the same output
  581. channel, but you'll have to handle `$-' (lines left on the page)
  582. yourself.
  583.  
  584.    If you are printing lots of fields that are usually blank, you should
  585. consider using the reset operator between records.  Not only is it more
  586. efficient, but it can prevent the bug of adding another field and
  587. forgetting to zero it.
  588.  
  589. 
  590. File: perl.info,  Node: Interprocess Communication,  Next: Predefined Names,  Prev: Formats,  Up: Top
  591.  
  592. Interprocess Communication
  593. **************************
  594.  
  595.    The IPC facilities of perl are built on the Berkeley socket
  596. mechanism.  If you don't have sockets, you can ignore this section.
  597. The calls have the same names as the corresponding system calls, but
  598. the arguments tend to differ, for two reasons.  First, perl file
  599. handles work differently than C file descriptors.  Second, perl already
  600. knows the length of its strings, so you don't need to pass that
  601. information.  Here is a sample client (untested):
  602.  
  603.      ($them,$port) = @ARGV;
  604.      $port = 2345 unless $port;
  605.      $them = 'localhost' unless $them;
  606.      
  607.      $SIG{'INT'} = 'dokill';
  608.      sub dokill { kill 9,$child if $child; }
  609.      
  610.      require 'sys/socket.ph';
  611.      
  612.      $sockaddr = 'S n a4 x8';
  613.      chop($hostname = `hostname`);
  614.      
  615.      ($name, $aliases, $proto) = getprotobyname('tcp');
  616.      ($name, $aliases, $port) = getservbyname($port, 'tcp')
  617.              unless $port =~ /^\d+$/;
  618.      ($name, $aliases, $type, $len, $thisaddr) =
  619.                                      gethostbyname($hostname);
  620.      ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
  621.      
  622.      $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
  623.      $that = pack($sockaddr, &AF_INET, $port, $thataddr);
  624.      
  625.      socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  626.      bind(S, $this) || die "bind: $!";
  627.      connect(S, $that) || die "connect: $!";
  628.      
  629.      select(S); $| = 1; select(stdout);
  630.      
  631.      if ($child = fork) {
  632.              while (<>) {
  633.                      print S;
  634.              }
  635.              sleep 3;
  636.              do dokill();
  637.      }
  638.      else {
  639.              while (<S>) {
  640.                      print;
  641.              }
  642.      }
  643.  
  644.    And here's a server:
  645.  
  646.      ($port) = @ARGV;
  647.      $port = 2345 unless $port;
  648.      
  649.      require 'sys/socket.ph';
  650.      
  651.      $sockaddr = 'S n a4 x8';
  652.      
  653.      ($name, $aliases, $proto) = getprotobyname('tcp');
  654.      ($name, $aliases, $port) = getservbyname($port, 'tcp')
  655.              unless $port =~ /^\d+$/;
  656.      
  657.      $this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");
  658.      
  659.      select(NS); $| = 1; select(stdout);
  660.      
  661.      socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  662.      bind(S, $this) || die "bind: $!";
  663.      listen(S, 5) || die "connect: $!";
  664.      
  665.      select(S); $| = 1; select(stdout);
  666.      
  667.      for (;;) {
  668.              print "Listening again\n";
  669.              ($addr = accept(NS,S)) || die $!;
  670.              print "accept ok\n";
  671.      
  672.              ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
  673.              @inetaddr = unpack('C4',$inetaddr);
  674.              print "$af $port @inetaddr\n";
  675.      
  676.              while (<NS>) {
  677.                      print;
  678.                      print NS;
  679.              }
  680.      }
  681.  
  682. 
  683. File: perl.info,  Node: Predefined Names,  Next: Packages,  Prev: Interprocess Communication,  Up: Top
  684.  
  685. Predefined Names
  686. ****************
  687.  
  688.    The following names have special meaning to *perl*.  I could have
  689. used alphabetic symbols for some of these, but I didn't want to take the
  690. chance that someone would say `reset "a-zA-Z"' and wipe them all out.
  691. You'll just have to suffer along with these silly symbols.  Most of
  692. them have reasonable mnemonics, or analogues in one of the shells.
  693.  
  694. $_
  695.      The default input and pattern-searching space.  The following
  696.      pairs are more or less equivalent:
  697.  
  698.           while (<>) {...    # only equivalent in while!
  699.           while ($_ = <>) {...
  700.           
  701.           /^Subject:/
  702.           $_ =~ /^Subject:/
  703.           
  704.           y/a-z/A-Z/
  705.           $_ =~ y/a-z/A-Z/
  706.           
  707.           chop
  708.           chop($_)
  709.  
  710.      (Mnemonic: underline is understood in certain operations.)
  711.  
  712. $.
  713.      The current input line number of the last filehandle that was read.
  714.      Readonly.  Remember that only an explicit close on the filehandle
  715.      resets the line number.  Since `<>' never does an explicit close,
  716.      line numbers increase across `ARGV' files (but see examples under
  717.      `eof').  (Mnemonic: many programs use `.' to mean the current line
  718.      number.)
  719.  
  720. $/
  721.      The input record separator, newline by default.  Works like `awk''s
  722.      RS variable, including treating blank lines as delimiters if set
  723.      to the null string.  You may set it to a multicharacter string to
  724.      match a multi-character delimiter.  Note that setting it to
  725.      `"\n\n"' means something slightly different than setting it to
  726.      `""', if the file contains consecutive blank lines.  Setting it to
  727.      `""' will treat two or more consecutive blank lines as a single
  728.      blank line.  Setting it to "\en\en" will blindly assume that the
  729.      next input character belongs to the next paragraph, even if it's a
  730.      newline.  (Mnemonic: `/' is used to delimit line boundaries when
  731.      quoting poetry.)
  732.  
  733. $,
  734.      The output field separator for the `print' operator.  Ordinarily
  735.      the `print' operator simply prints out the comma separated fields
  736.      you specify.  In order to get behavior more like `awk', set this
  737.      variable as you would set `awk''s OFS variable to specify what is
  738.      printed between fields.  (Mnemonic: what is printed when there is
  739.      a `,' in your print statement.)
  740.  
  741. $"
  742.      This is like `$,' except that it applies to array values
  743.      interpolated into a double-quoted string (or similar interpreted
  744.      string).  Default is a space.  (Mnemonic: obvious, I think.)
  745.  
  746. $\
  747.      The output record separator for the `print' operator.  Ordinarily
  748.      the `print' operator simply prints out the comma separated fields
  749.      you specify, with no trailing newline or record separator assumed.
  750.      In order to get behavior more like `awk', set this variable as
  751.      you would set `awk''s ORS variable to specify what is printed at
  752.      the end of the print.  (Mnemonic: you set `$\' instead of adding
  753.      `\n' at the end of the print.  Also, it's just like `/', but it's
  754.      what you get "back" from *perl*.)
  755.  
  756. $#
  757.      The output format for printed numbers.  This variable is a
  758.      half-hearted attempt to emulate `awk''s OFMT variable.  There are
  759.      times, however, when `awk' and *perl* have differing notions of
  760.      what is in fact numeric.  Also, the initial value is `%.20g'
  761.      rather than `%.6g', so you need to set `$#' explicitly to get
  762.      `awk''s value.  (Mnemonic: `#' is the number sign.)
  763.  
  764. $%
  765.      The current page number of the currently selected output channel.
  766.      (Mnemonic: `%' is page number in nroff.)
  767.  
  768. $=
  769.      The current page length (printable lines) of the currently selected
  770.      output channel.  Default is 60.  (Mnemonic: `=' has horizontal
  771.      lines.)
  772.  
  773. $-
  774.      The number of lines left on the page of the currently selected
  775.      output channel.  (Mnemonic: lines_on_page - lines_printed.)
  776.  
  777. $~
  778.      The name of the current report format for the currently selected
  779.      output channel.  Default is name of the filehandle.  (Mnemonic:
  780.      brother to `$^'.)
  781.  
  782. $^
  783.      The name of the current top-of-page format for the currently
  784.      selected output channel.  Default is name of the filehandle with
  785.      `_TOP' appended.  (Mnemonic: points to top of page.)
  786.  
  787. $|
  788.      If set to nonzero, forces a flush after every `write' or `print'
  789.      on the currently selected output channel.  Default is 0.  Note that
  790.      `STDOUT' will typically be line buffered if output is to the
  791.      terminal and block buffered otherwise.  Setting this variable is
  792.      useful primarily when you are outputting to a pipe, such as when
  793.      you are running a *perl* script under rsh and want to see the
  794.      output as it's happening.  (Mnemonic: when you want your pipes to
  795.      be piping hot.)
  796.  
  797. $$
  798.      The process number of the *perl* running this script.  (Mnemonic:
  799.      same as shells.)
  800.  
  801. $?
  802.      The status returned by the last pipe close, backtick (``) command
  803.      or `system' operator.  Note that this is the status word returned
  804.      by the `wait()' system call, so the exit value of the subprocess is
  805.      actually `($? >> 8)'.  `$? & 255' gives which signal, if any, the
  806.      process died from, and whether there was a core dump.  (Mnemonic:
  807.      similar to `sh' and `ksh'.)
  808.  
  809. $&
  810.      The string matched by the last successful pattern match (not
  811.      counting any matches hidden within a BLOCK or `eval' enclosed by
  812.      the current BLOCK).  (Mnemonic: like `&' in some editors.)
  813.  
  814. $`
  815.      The string preceding whatever was matched by the last successful
  816.      pattern match (not counting any matches hidden within a BLOCK or
  817.      `eval' enclosed by the current BLOCK).  (Mnemonic: ` often
  818.      precedes a quoted string.)
  819.  
  820. $'
  821.      The string following whatever was matched by the last successful
  822.      pattern match (not counting any matches hidden within a BLOCK or
  823.      `eval' enclosed by the current BLOCK).  (Mnemonic: ' often follows
  824.      a quoted string.) Example:
  825.  
  826.           $_ = 'abcdefghi';
  827.           /def/;
  828.           print "$`:$&:$'\n";     # prints abc:def:ghi
  829.  
  830. $+
  831.      The last bracket matched by the last search pattern.  This is
  832.      useful if you don't know which of a set of alternative patterns
  833.      matched.  For example:
  834.  
  835.           /Version: (.*)|Revision: (.*)/ && ($rev = $+);
  836.  
  837.      (Mnemonic: be positive and forward looking.)
  838.  
  839. $*
  840.      Set to 1 to do multiline matching within a string, 0 to tell *perl*
  841.      that it can assume that strings contain a single line, for the
  842.      purpose of optimizing pattern matches.  Pattern matches on strings
  843.      containing multiple newlines can produce confusing results when
  844.      `$*' is 0.  Default is 0.  Note that this variable only influences
  845.      the interpretation of `^' and `$'.  A literal newline can be
  846.      searched for even when `$* == 0'.  (Mnemonic: `*' matches multiple
  847.      things.)
  848.  
  849. $0
  850.      Contains the name of the file containing the *perl* script being
  851.      executed.  Assigning to `$0' modifies the argument area that the
  852.      `ps(1)' program sees.  (Mnemonic: same as `sh' and `ksh'.)
  853.  
  854. $<digit>
  855.      Contains the subpattern from the corresponding set of parentheses
  856.      in the last pattern matched, not counting patterns matched in
  857.      nested blocks that have been exited already.  (Mnemonic: like
  858.      `\digit'.)
  859.  
  860. $[
  861.      The index of the first element in an array, and of the first
  862.      character in a substring.  Default is 0, but you could set it to 1
  863.      to make *perl* behave more like `awk' (or Fortran) when
  864.      subscripting and when evaluating the `index()' and `substr()'
  865.      functions.  (Mnemonic: `[' begins subscripts.)
  866.  
  867. $]
  868.      The string printed out when you say `perl -v'.  It can be used to
  869.      determine at the beginning of a script whether the perl interpreter
  870.      executing the script is in the right range of versions.  If used
  871.      in a numeric context, returns the version + patchlevel / 1000.
  872.      Example:
  873.  
  874.           # see if getc is available
  875.           ($version,$patchlevel) =
  876.                    $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
  877.           print STDERR "(No filename completion available.)\n"
  878.                    if $version * 1000 + $patchlevel < 2016;
  879.  
  880.      or, used numerically,
  881.  
  882.           warn "No checksumming!\n" if $] < 3.019;
  883.  
  884.      (Mnemonic: Is this version of perl in the right bracket?)
  885.  
  886. $;
  887.      The subscript separator for multi-dimensional array emulation.  If
  888.      you refer to an associative array element as
  889.  
  890.           $foo{$a,$b,$c}
  891.  
  892.      it really means
  893.  
  894.           $foo{join($;, $a, $b, $c)}
  895.  
  896.      But don't put
  897.  
  898.           @foo{$a,$b,$c}           # a slice--note the @
  899.  
  900.      which means
  901.  
  902.           ($foo{$a},$foo{$b},$foo{$c})
  903.  
  904.      Default is `\034', the same as SUBSEP in `awk'.  Note that if your
  905.      keys contain binary data there might not be any safe value for
  906.      `$;'.  (Mnemonic: comma (the syntactic subscript separator) is a
  907.      semi-semicolon.  Yeah, I know, it's pretty lame, but `$,' is
  908.      already taken for something more important.)
  909.  
  910. $!
  911.      If used in a numeric context, yields the current value of errno,
  912.      with all the usual caveats.  (This means that you shouldn't depend
  913.      on the value of `$!' to be anything in particular unless you've
  914.      gotten a specific error return indicating a system error.)  If
  915.      used in a string context, yields the corresponding system error
  916.      string.  You can assign to `$!' in order to set errno if, for
  917.      instance, you want `$!' to return the string for error N, or you
  918.      want to set the exit value for the `die' operator.  (Mnemonic:
  919.      What just went bang?)
  920.  
  921. $@
  922.      The perl syntax error message from the last `eval' command.  If
  923.      null, the last `eval' parsed and executed correctly (although the
  924.      operations you invoked may have failed in the normal fashion).
  925.      (Mnemonic: Where was the syntax error "at"?)
  926.  
  927. $<
  928.      The real uid of this process.  (Mnemonic: it's the uid you came
  929.      *FROM*, if you're running setuid.)
  930.  
  931. $>
  932.      The effective uid of this process.  Example:
  933.  
  934.           $< = $>;              # set real uid to the effective uid
  935.           ($<,$>) = ($>,$<);    # swap real and effective uid
  936.  
  937.      (Mnemonic: it's the uid you went *TO*, if you're running setuid.)
  938.      Note: `$<' and `$>' can only be swapped on machines supporting
  939.      `setreuid()'.
  940.  
  941. $(
  942.      The real gid of this process.  If you are on a machine that
  943.      supports membership in multiple groups simultaneously, gives a
  944.      space separated list of groups you are in.  The first number is
  945.      the one returned by `getgid()', and the subsequent ones by
  946.      `getgroups()', one of which may be the same as the first number.
  947.      (Mnemonic: parentheses are used to *GROUP* things.  The real gid
  948.      is the group you *LEFT*, if you're running setgid.)
  949.  
  950. $)
  951.      The effective gid of this process.  If you are on a machine that
  952.      supports membership in multiple groups simultaneously, gives a
  953.      space separated list of groups you are in.  The first number is
  954.      the one returned by `getegid()', and the subsequent ones by
  955.      `getgroups()', one of which may be the same as the first number.
  956.      (Mnemonic: parentheses are used to *GROUP* things.  The effective
  957.      gid is the group that's *RIGHT* for you, if you're running setgid.)
  958.  
  959.      Note: `$<', `$>', `$(' and `$)' can only be set on machines that
  960.      support the corresponding `set[re][ug]id()' routine.  `$(' and
  961.      `$)' can only be swapped on machines supporting `setregid()'.
  962.  
  963. $:
  964.      The current set of characters after which a string may be broken
  965.      to fill continuation fields (starting with `^') in a format.
  966.      Default is ` \n-', to break on whitespace or hyphens.  (Mnemonic:
  967.      a "colon" in poetry is a part of a line.)
  968.  
  969. $^D
  970.      The current value of the debugging flags.  (Mnemonic: value of `-D'
  971.      switch.)
  972.  
  973. $^F
  974.      The maximum system file descriptor, ordinarily 2.  System file
  975.      descriptors are passed to subprocesses, while higher file
  976.      descriptors are not.  During an open, system file descriptors are
  977.      preserved even if the open fails.  Ordinary file descriptors are
  978.      closed before the open is attempted.
  979.  
  980. $^I
  981.      The current value of the inplace-edit extension.  Use `undef' to
  982.      disable inplace editing.  (Mnemonic: value of `-i' switch.)
  983.  
  984. $^L
  985.      What formats output to perform a formfeed.  Default is `\f'.
  986.  
  987. $^P
  988.      The internal flag that the debugger clears so that it doesn't debug
  989.      itself.  You could conceivably disable debugging yourself by
  990.      clearing it.
  991.  
  992. $^T
  993.      The time at which the script began running, in seconds since the
  994.      epoch.  The values returned by the `-M', `-A', and `-C' filetests
  995.      are based on this value.
  996.  
  997. $^W
  998.      The current value of the warning switch.  (Mnemonic: related to the
  999.      `-w' switch.)
  1000.  
  1001. $^X
  1002.      The name that Perl itself was executed as, from argv[0].
  1003.  
  1004. $ARGV
  1005.      The scalar variable `$ARGV' contains the name of the current file
  1006.      when reading from `<>'.
  1007.  
  1008. @ARGV
  1009.      The array `ARGV' contains the command line arguments intended for
  1010.      the script.  Note that `$#ARGV' is the generally number of
  1011.      arguments minus one, since `$ARGV[0]' is the first argument, *NOT*
  1012.      the command name.  See `$0' for the command name.
  1013.  
  1014. @INC
  1015.      The array `INC' contains the list of places to look for *perl*
  1016.      scripts to be evaluated by the `do EXPR' command or the `require'
  1017.      command.  It initially consists of the arguments to any `-I'
  1018.      command line switches, followed by the default *perl* library,
  1019.      probably `/usr/local/lib/perl', followed by `.', to represent the
  1020.      current directory.
  1021.  
  1022. %INC
  1023.      The associative array `INC' contains entries for each filename that
  1024.      has been included via `do' or `require'.  The key is the filename
  1025.      you specified, and the value is the location of the file actually
  1026.      found.  The `require' command uses this array to determine whether
  1027.      a given file has already been included.
  1028.  
  1029. $ENV{expr}
  1030.      The associative array `ENV' contains your current environment.
  1031.      Setting a value in `ENV' changes the environment for child
  1032.      processes.
  1033.  
  1034. $SIG{expr}
  1035.      The associative array `SIG' is used to set signal handlers for
  1036.      various signals.  Example:
  1037.  
  1038.           sub handler {  # 1st argument is signal name
  1039.                   local($sig) = @_;
  1040.                   print "Caught a SIG$sig--shutting down\n";
  1041.                   close(LOG);
  1042.                   exit(0);
  1043.           }
  1044.           
  1045.           $SIG{'INT'} = 'handler';
  1046.           $SIG{'QUIT'} = 'handler';
  1047.           ...
  1048.           $SIG{'INT'} = 'DEFAULT';      # restore default action
  1049.           $SIG{'QUIT'} = 'IGNORE';      # ignore SIGQUIT
  1050.  
  1051.      The `SIG' array only contains values for the signals actually set
  1052.      within the perl script.
  1053.  
  1054. 
  1055. File: perl.info,  Node: Packages,  Next: Style,  Prev: Predefined Names,  Up: Top
  1056.  
  1057. Packages
  1058. ********
  1059.  
  1060.    Perl provides a mechanism for alternate namespaces to protect
  1061. packages from stomping on each others variables.  By default, a perl
  1062. script starts compiling into the package known as `main'.  By use of the
  1063. `package' declaration, you can switch namespaces.  The scope of the
  1064. `package' declaration is from the declaration itself to the end of the
  1065. enclosing block (the same scope as the `local()' operator).  Typically
  1066. it would be the first declaration in a file to be included by the
  1067. `require' operator.  You can switch into a package in more than one
  1068. place; it merely influences which symbol table is used by the compiler
  1069. for the rest of that block.  You can refer to variables and filehandles
  1070. in other packages by prefixing the identifier with the package name and
  1071. a single quote.  If the package name is null, the `main' package as
  1072. assumed.
  1073.  
  1074.    Only identifiers starting with letters are stored in the packages
  1075. symbol table.  All other symbols are kept in package `main'.  In
  1076. addition, the identifiers `STDIN', `STDOUT', `STDERR', `ARGV',
  1077. `ARGVOUT', `ENV', `INC' and `SIG' are forced to be in package `main',
  1078. even when used for other purposes than their built-in one.  Note also
  1079. that, if you have a package called `m', `s' or `y', the you can't use
  1080. the qualified form of an identifier since it will be interpreted
  1081. instead as a pattern match, a substitution or a translation.
  1082.  
  1083.    `eval''ed strings are compiled in the package in which the `eval'
  1084. was compiled in.  (Assignments to `$SIG{}', however, assume the signal
  1085. handler specified is in the `main' package.  Qualify the signal handler
  1086. name if you wish to have a signal handler in a package.)  For an
  1087. example, examine `perldb.pl' in the perl library.  It initially
  1088. switches to the `DB' package so that the debugger doesn't interfere
  1089. with variables in the script you are trying to debug.  At various
  1090. points, however, it temporarily switches back to the `main' package to
  1091. evaluate various expressions in the context of the `main' package.
  1092.  
  1093.    The symbol table for a package happens to be stored in the
  1094. associative array of that name prepended with an underscore.  The value
  1095. in each entry of the associative array is what you are referring to
  1096. when you use the `*name' notation.  In fact, the following have the
  1097. same effect (in package `main', anyway), though the first is more
  1098. efficient because it does the symbol table lookups at compile time:
  1099.  
  1100.      local(*foo) = *bar;
  1101.      local($_main{'foo'}) = $_main{'bar'};
  1102.  
  1103.    You can use this to print out all the variables in a package, for
  1104. instance.  Here is `dumpvar.pl' from the perl library:
  1105.  
  1106.      package dumpvar;
  1107.      
  1108.      sub main'dumpvar {
  1109.          ($package) = @_;
  1110.          local(*stab) = eval("*_$package");
  1111.          while (($key,$val) = each(%stab)) {
  1112.              {
  1113.                  local(*entry) = $val;
  1114.                  if (defined $entry) {
  1115.                      print "\$$key = '$entry'\n";
  1116.                  }
  1117.                  if (defined @entry) {
  1118.                      print "\@$key = (\n";
  1119.                      foreach $num ($[ .. $#entry) {
  1120.                          print "  $num\t'",$entry[$num],"'\n";
  1121.                      }
  1122.                      print ")\n";
  1123.                  }
  1124.                  if ($key ne "_$package" && defined %entry) {
  1125.                      print "\%$key = (\n";
  1126.                      foreach $key (sort keys(%entry)) {
  1127.                          print "  $key\t'",$entry{$key},"'\n";
  1128.                      }
  1129.                      print ")\n";
  1130.                  }
  1131.              }
  1132.          }
  1133.      }
  1134.  
  1135.    Note that, even though the subroutine is compiled in package
  1136. `dumpvar', the name of the subroutine is qualified so that its name is
  1137. inserted into package `main'.
  1138.  
  1139. 
  1140. File: perl.info,  Node: Style,  Next: Debugging,  Prev: Packages,  Up: Top
  1141.  
  1142. Style
  1143. *****
  1144.  
  1145.    Each programmer will, of course, have his or her own preferences in
  1146. regards to formatting, but there are some general guidelines that will
  1147. make your programs easier to read.
  1148.  
  1149.   1. Just because you *CAN* do something a particular way doesn't mean
  1150.      that you *SHOULD* do it that way.  *Perl* is designed to give you
  1151.      several ways to do anything, so consider picking the most readable
  1152.      one.  For instance
  1153.  
  1154.           open(FOO,$foo) || die "Can't open $foo: $!";
  1155.  
  1156.      is better than
  1157.  
  1158.           die "Can't open $foo: $!" unless open(FOO,$foo);
  1159.  
  1160.      because the second way hides the main point of the statement in a
  1161.      modifier.  On the other hand
  1162.  
  1163.           print "Starting analysis\n" if $verbose;
  1164.  
  1165.      is better than
  1166.  
  1167.           $verbose && print "Starting analysis\n";
  1168.  
  1169.      since the main point isn't whether the user typed `-v' or not.
  1170.  
  1171.      Similarly, just because an operator lets you assume default
  1172.      arguments doesn't mean that you have to make use of the defaults.
  1173.      The defaults are there for lazy systems programmers writing
  1174.      one-shot programs.  If you want your program to be readable,
  1175.      consider supplying the argument.
  1176.  
  1177.      Along the same lines, just because you *can* omit parentheses in
  1178.      many places doesn't mean that you ought to:
  1179.  
  1180.           return print reverse sort num values array;
  1181.           return print(reverse(sort num (values(%array))));
  1182.  
  1183.      When in doubt, parenthesize.  At the very least it will let some
  1184.      poor schmuck bounce on the `%' key in *vi*.
  1185.  
  1186.      Even if you aren't in doubt, consider the mental welfare of the
  1187.      person who has to maintain the code after you, and who will
  1188.      probably put parens in the wrong place.
  1189.  
  1190.   2. Don't go through silly contortions to exit a loop at the top or
  1191.      the bottom, when *perl* provides the `last' operator so you can
  1192.      exit in the middle.  Just outdent it a little to make it more
  1193.      visible:
  1194.  
  1195.           line:
  1196.               for (;;) {
  1197.                   statements;
  1198.               last line if $foo;
  1199.                   next line if /^#/;
  1200.                   statements;
  1201.               }
  1202.  
  1203.   3. Don't be afraid to use loop labels--they're there to enhance
  1204.      readability as well as to allow multi-level loop breaks.  See last
  1205.      example.
  1206.  
  1207.   4. For portability, when using features that may not be implemented
  1208.      on every machine, test the construct in an `eval' to see if it
  1209.      fails.  If you know what version or patchlevel a particular
  1210.      feature was implemented, you can test `$]' to see if it will be
  1211.      there.
  1212.  
  1213.   5. Choose mnemonic identifiers.
  1214.  
  1215.   6. Be consistent.
  1216.  
  1217.