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-2 < prev    next >
Encoding:
GNU Info File  |  1994-07-08  |  47.9 KB  |  1,218 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: Data Types,  Next: Syntax,  Prev: Perl Startup,  Up: Top
  32.  
  33. Data Types and Objects
  34. **********************
  35.  
  36.    *Perl* has three data types: scalars, arrays of scalars, and
  37. associative arrays of scalars.  Normal arrays are indexed by number,
  38. and associative arrays by string.
  39.  
  40.    The interpretation of operations and values in perl sometimes
  41. depends on the requirements of the context around the operation or
  42. value.  There are three major contexts: "string", "numeric" and "array".
  43. Certain operations return array values in contexts wanting an array, and
  44. scalar values otherwise.  (If this is true of an operation it will be
  45. mentioned in the documentation for that operation.)  Operations which
  46. return scalars don't care whether the context is looking for a string or
  47. a number, but scalar variables and values are interpreted as strings or
  48. numbers as appropriate to the context.  A scalar is interpreted as TRUE
  49. in the boolean sense if it is not the null string or 0.  Booleans
  50. returned by operators are 1 for TRUE and 0 or '' (the null string [two
  51. single right quotes]) for FALSE.
  52.  
  53.    There are actually two varieties of null strings: "defined" and
  54. "undefined".  Undefined null strings are returned when there is no real
  55. value for something, such as when there was an error, or at end of
  56. file, or when you refer to an uninitialized variable or element of an
  57. array.  An undefined null string may become defined the first time you
  58. access it, but prior to that you can use the `defined()' operator to
  59. determine whether the value is defined or not.
  60.  
  61.    References to scalar variables always begin with `$', even when
  62. referring to a scalar that is part of an array.  Thus:
  63.  
  64.      $days               # a simple scalar variable
  65.      $days[28]           # 29th element of array @days
  66.      $days{'Feb'}        # one value from an associative array
  67.      $#days              # last index of array @days
  68.  
  69. but entire arrays or array slices are denoted by `@':
  70.  
  71.      @days              # ($days[0], $days[1],... $days[n])
  72.      @days[3,4,5]       # same as @days[3..5]
  73.      @days{'a','c'}     # same as ($days{'a'},$days{'c'})
  74.  
  75. and entire associative arrays are denoted by `%':
  76.  
  77.      %days               # (key1, val1, key2, val2 ...)
  78.  
  79.    Any of these eight constructs may serve as an lvalue, that is, may be
  80. assigned to.  (It also turns out that an assignment is itself an lvalue
  81. in certain contexts--see examples under `s', `tr' and `chop'.)
  82. Assignment to a scalar evaluates the righthand side in a scalar
  83. context, while assignment to an array or array slice evaluates the
  84. righthand side in an array context.
  85.  
  86.    You may find the length of array `@days' by evaluating `$#days', as
  87. in `csh'.  (Actually, it's not the length of the array, it's the
  88. subscript of the last element, since there is (ordinarily) a 0th
  89. element.)  Assigning to `$#days' changes the length of the array.
  90. Shortening an array by this method does not actually destroy any
  91. values.  Lengthening an array that was previously shortened recovers
  92. the values that were in those elements.  You can also gain some measure
  93. of efficiency by preextending an array that is going to get big.  (You
  94. can also extend an array by assigning to an element that is off the end
  95. of the array.  This differs from assigning to `$#whatever' in that
  96. intervening values are set to null rather than recovered.)  You can
  97. truncate an array down to nothing by assigning the null list `()' to
  98. it.  The following are exactly equivalent:
  99.  
  100.      @whatever = ();
  101.      $#whatever = $[ - 1;
  102.  
  103. If you evaluate an array in a scalar context, it returns the length of
  104. the array.  The following is always true:
  105.  
  106.      scalar(@whatever) == $#whatever - $[ + 1;
  107.  
  108.    If you evaluate an associative array in a scalar context, it returns
  109. a value which is true if and only if the array contains any elements.
  110. (If there are any elements, the value returned is a string consisting
  111. of the number of used buckets and the number of allocated buckets,
  112. separated by a slash.)
  113.  
  114.    Multi-dimensional arrays are not directly supported, but see the
  115. discussion of the `$;' variable later for a means of emulating multiple
  116. subscripts with an associative array.  You could also write a
  117. subroutine to turn multiple subscripts into a single subscript.
  118.  
  119.    Every data type has its own namespace.  You can, without fear of
  120. conflict, use the same name for a scalar variable, an array, an
  121. associative array, a filehandle, a subroutine name, and/or a label.
  122. Since variable and array references always start with `$', `@', or `%',
  123. the "reserved" words aren't in fact reserved with respect to variable
  124. names.  (They *ARE* reserved with respect to labels and filehandles,
  125. however, which don't have an initial special character.  Hint: you
  126. could say `open(LOG,'logfile')' rather than `open(log,'logfile')'.
  127. Using uppercase filehandles also improves readability and protects you
  128. from conflict with future reserved words.)  Case *IS*
  129. significant--`FOO', `Foo' and `foo' are all different names.  Names
  130. which start with a letter may also contain digits and underscores.
  131. Names which do not start with a letter are limited to one character,
  132. e.g. `$%' or `$$'.  (Most of the one character names have a predefined
  133. significance to *perl*.  More later.)
  134.  
  135.    Numeric literals are specified in any of the usual floating point or
  136. integer formats:
  137.  
  138.      12345
  139.      12345.67
  140.      .23E-10
  141.      0xffff      # hex
  142.      0377        # octal
  143.      4_294_967_296
  144.  
  145.    String literals are delimited by either single or double quotes.
  146. They work much like shell quotes: double-quoted string literals are
  147. subject to backslash and variable substitution; single-quoted strings
  148. are not (except for \' and \\).  The usual backslash rules apply for
  149. making characters such as newline, tab, etc., as well as some more
  150. exotic forms:
  151.  
  152.      \t      tab
  153.      \n      newline
  154.      \r      return
  155.      \f      form feed
  156.      \b      backspace
  157.      \a      alarm (bell)
  158.      \e      escape
  159.      \033    octal char
  160.      \x1b    hex char
  161.      \c[     control char
  162.      \l      lowercase next char
  163.      \u      uppercase next char
  164.      \L      lowercase till \E
  165.      \U      uppercase till \E
  166.      \E      end case modification
  167.  
  168.    You can also embed newlines directly in your strings, i.e. they can
  169. end on a different line than they begin.  This is nice, but if you
  170. forget your trailing quote, the error will not be reported until *perl*
  171. finds another line containing the quote character, which may be much
  172. further on in the script.  Variable substitution inside strings is
  173. limited to scalar variables, normal array values, and array slices.  (In
  174. other words, identifiers beginning with `$' or `@', followed by an
  175. optional bracketed expression as a subscript.)  The following code
  176. segment prints out `The price is $100.'
  177.  
  178.      $Price = '$100';                    # not interpreted
  179.      print "The price is $Price.\n";     # interpreted
  180.  
  181.    Note that you can put curly brackets around the identifier to
  182. delimit it from following alphanumerics.  Also note that a single
  183. quoted string must be separated from a preceding word by a space, since
  184. single quote is a valid character in an identifier.  *Note Packages::,
  185. for more info.
  186.  
  187.    Two special literals are `__LINE__' and `__FILE__', which represent
  188. the current line number and filename at that point in your program.
  189. They may only be used as separate tokens; they will not be interpolated
  190. into strings.  In addition, the token `__END__' may be used to indicate
  191. the logical end of the script before the actual end of file.  Any
  192. following text is ignored, but may be read via the `DATA' filehandle.
  193. (The `DATA' filehandle may read data only from the main script, but not
  194. from any required file or evaluated string.) The two control characters
  195. D' and Z' are synonyms for `__END__'.
  196.  
  197.    A word that doesn't have any other interpretation in the grammar
  198. will be treated as if it had single quotes around it.  For this
  199. purpose, a word consists only of alphanumeric characters and underline,
  200. and must start with an alphabetic character.  As with filehandles and
  201. labels, a bare word that consists entirely of lowercase letters risks
  202. conflict with future reserved words, and if you use the `-w' switch,
  203. *perl* will warn you about any such words.
  204.  
  205.    Array values are interpolated into double-quoted strings by joining
  206. all the elements of the array with the delimiter specified in the `$"'
  207. variable, space by default.  (Since in versions of perl prior to 3.0 the
  208. `@' character was not a metacharacter in double-quoted strings, the
  209. interpolation of `@array', `$array[EXPR]', `@array[LIST]',
  210. `$array{EXPR}', or `@array{LIST}' only happens if array is referenced
  211. elsewhere in the program or is predefined.)  The following are
  212. equivalent:
  213.  
  214.      $temp = join($",@ARGV);
  215.      system "echo $temp";
  216.      system "echo @ARGV";
  217.  
  218.    Within search patterns (which also undergo double-quotish
  219. substitution) there is a bad ambiguity: Is `/$foo[bar]/' to be
  220. interpreted as `/${foo}[bar]/' (where `[bar]' is a character class for
  221. the regular expression) or as `/${foo[bar]}/' (where `[bar]' is the
  222. subscript to array `@foo')?  If `@foo' doesn't otherwise exist, then
  223. it's obviously a character class.  If `@foo' exists, perl takes a good
  224. guess about `[bar]', and is almost always right.  If it does guess
  225. wrong, or if you're just plain paranoid, you can force the correct
  226. interpretation with curly brackets as above.
  227.  
  228.    A line-oriented form of quoting is based on the shell here-is syntax.
  229. Following a `<<' you specify a string to terminate the quoted material,
  230. and all lines following the current line down to the terminating string
  231. are the value of the item.  The terminating string may be either an
  232. identifier (a word), or some quoted text.  If quoted, the type of
  233. quotes you use determines the treatment of the text, just as in regular
  234. quoting.  An unquoted identifier works like double quotes.  There must
  235. be no space between the `<<' and the identifier.  (If you put a space
  236. it will be treated as a null identifier, which is valid, and matches
  237. the first blank line--see Merry Christmas example below.) The
  238. terminating string must appear by itself (unquoted and with no
  239. surrounding whitespace) on the terminating line.
  240.  
  241.              print <<EOF;            # same as above
  242.      The price is $Price.
  243.      EOF
  244.      
  245.              print <<"EOF";          # same as above
  246.      The price is $Price.
  247.      EOF
  248.      
  249.              print << x 10;          # null identifier is delimiter
  250.      Merry Christmas!
  251.      
  252.              print <<`EOC`;          # execute commands
  253.      echo hi there
  254.      echo lo there
  255.      EOC
  256.      
  257.              print <<foo, <<bar;     # you can stack them
  258.      I said foo.
  259.      foo
  260.      I said bar.
  261.      bar
  262.  
  263.    Array literals are denoted by separating individual values by
  264. commas, and enclosing the list in parentheses:
  265.  
  266.      (LIST)
  267.  
  268.    In a context not requiring an array value, the value of the array
  269. literal is the value of the final element, as in the C comma operator.
  270. For example,
  271.  
  272.      @foo = ('cc', '-E', $bar);
  273.  
  274. assigns the entire array value to array FOO, but
  275.  
  276.      $foo = ('cc', '-E', $bar);
  277.  
  278. assigns the value of variable BAR to variable FOO.  Note that the value
  279. of an actual array in a scalar context is the length of the array; the
  280. following assigns to `$foo' the value 3:
  281.  
  282.      @foo = ('cc', '-E', $bar);
  283.      $foo = @foo;               # $foo gets 3
  284.  
  285. You may have an optional comma before the closing parenthesis of an
  286. array literal, so that you can say:
  287.  
  288.      @foo = (
  289.          1,
  290.          2,
  291.          3,
  292.      );
  293.  
  294.    When a LIST is evaluated, each element of the list is evaluated in
  295. an array context, and the resulting array value is interpolated into
  296. LIST just as if each individual element were a member of LIST.  Thus
  297. arrays lose their identity in a LIST--the list
  298.  
  299.      (@foo,@bar,&SomeSub)
  300.  
  301. contains all the elements of `@foo' followed by all the elements of
  302. `@bar', followed by all the elements returned by the subroutine named
  303. `SomeSub'.
  304.  
  305. A list value may also be subscripted like a normal array.  Examples:
  306.  
  307.      $time = (stat($file))[8];       # stat returns array value
  308.      $digit = ('a','b','c','d','e','f')[$digit-10];
  309.      return (pop(@foo),pop(@foo))[0];
  310.  
  311. Array lists may be assigned to *if and only if* each element of the
  312. list is an lvalue:
  313.  
  314.      ($a, $b, $c) = (1, 2, 3);
  315.      
  316.      ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  317.  
  318. The final element may be an array or an associative array:
  319.  
  320.      ($a, $b, @rest) = split;
  321.      local($a, $b, %rest) = @_;
  322.  
  323. You can actually put an array anywhere in the list, but the first array
  324. in the list will soak up all the values, and anything after it will get
  325. a null value.  This may be useful in a `local()'.
  326.  
  327. An associative array literal contains pairs of values to be interpreted
  328. as a key and a value:
  329.  
  330.      # same as map assignment above
  331.      %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  332.  
  333. Array assignment in a scalar context returns the number of elements
  334. produced by the expression on the right side of the assignment:
  335.  
  336.      $x = (($foo,$bar) = (3,2,1));   # set $x to 3, not 2
  337.  
  338.    There are several other pseudo-literals that you should know about.
  339. If a string is enclosed by backticks (grave accents), it first undergoes
  340. variable substitution just like a double quoted string.  It is then
  341. interpreted as a command, and the output of that command is the value of
  342. the pseudo-literal, like in a shell.  In a scalar context, a single
  343. string consisting of all the output is returned.  In an array context,
  344. an array of values is returned, one for each line of output.  (You can
  345. set `$/' to use a different line terminator.)  The command is executed
  346. each time the pseudo-literal is evaluated.  The status value of the
  347. command is returned in `$?' (*Note Predefined Names::, for the
  348. interpretation of `$?').  Unlike in `csh', no translation is done on
  349. the return data--newlines remain newlines.  Unlike in any of the
  350. shells, single quotes do not hide variable names in the command from
  351. interpretation.  To pass a `$' through to the shell you need to hide it
  352. with a backslash.
  353.  
  354.    Evaluating a filehandle in angle brackets yields the next line from
  355. that file (newline included, so it's never false until EOF, at which
  356. time the undefined value is returned).  Ordinarily you must assign that
  357. value to a variable, but there is one situation where an automatic
  358. assignment happens.  If (and only if) the input symbol is the only
  359. thing inside the conditional of a `while' loop, the value is
  360. automatically assigned to the variable `$_'.  (This may seem like an
  361. odd thing to you, but you'll use the construct in almost every *perl*
  362. script you write.) Anyway, the following lines are equivalent to each
  363. other:
  364.  
  365.      while ($_ = <STDIN>) { print; }
  366.      while (<STDIN>) { print; }
  367.      for (;<STDIN>;) { print; }
  368.      print while $_ = <STDIN>;
  369.      print while <STDIN>;
  370.  
  371.    The filehandles `STDIN', `STDOUT' and `STDERR' are predefined.  (The
  372. filehandles `stdin', `stdout' and `stderr' will also work except in
  373. packages, where they would be interpreted as local identifiers rather
  374. than global.)  Additional filehandles may be created with the `open'
  375. function.
  376.  
  377.    If a `<FILEHANDLE>' is used in a context that is looking for an
  378. array, an array consisting of all the input lines is returned, one line
  379. per array element.  It's easy to make a LARGE data space this way, so
  380. use with care.
  381.  
  382.    The null filehandle `<>' is special and can be used to emulate the
  383. behavior of `sed' and `awk'.  Input from `<>' comes either from
  384. standard input, or from each file listed on the command line.  Here's
  385. how it works: the first time `<>' is evaluated, the `ARGV' array is
  386. checked, and if it is null, `$ARGV[0]' is set to `-', which when opened
  387. gives you standard input.  The `ARGV' array is then processed as a list
  388. of filenames.  The loop
  389.  
  390.      while (<>) {
  391.              ...                 # code for each line
  392.      }
  393.  
  394. is equivalent to the following Perl-like pseudo code:
  395.  
  396.      unshift(@ARGV, '-') if $#ARGV < $[;
  397.      while ($ARGV = shift) {
  398.              open(ARGV, $ARGV);
  399.              while (<ARGV>) {
  400.                      ...         # code for each line
  401.              }
  402.      }
  403.  
  404. except that it isn't as cumbersome to say, and will actually work.  It
  405. really does shift array `ARGV' and put the current filename into
  406. variable `ARGV'.  It also uses filehandle `ARGV' internally--`<>' is
  407. just a synonym for `<ARGV>', which is magical.  (The pseudo code above
  408. doesn't work because it treats `<ARGV>' as non-magical.)
  409.  
  410.    You can modify `@ARGV' before the first `<>' as long as the array
  411. ends up containing the list of filenames you really want.  Line numbers
  412. (`$.') continue as if the input was one big happy file.  (But see
  413. example under `eof' for how to reset line numbers on each file.)
  414.  
  415.    If you want to set `@ARGV' to your own list of files, go right
  416. ahead.  If you want to pass switches into your script, you can put a
  417. loop on the front like this:
  418.  
  419.      while ($_ = $ARGV[0], /^-/) {
  420.              shift;
  421.          last if /^--$/;
  422.              /^-D(.*)/ && ($debug = $1);
  423.              /^-v/ && $verbose++;
  424.              ...         # other switches
  425.      }
  426.      while (<>) {
  427.              ...         # code for each line
  428.      }
  429.  
  430.    The `<>' symbol will return FALSE only once.  If you call it again
  431. after this it will assume you are processing another `@ARGV' list, and
  432. if you haven't set `@ARGV', will input from `STDIN'.
  433.  
  434.    If the string inside the angle brackets is a reference to a scalar
  435. variable (e.g. `<$foo>'), then that variable contains the name of the
  436. filehandle to input from.
  437.  
  438.    If the string inside angle brackets is not a filehandle, it is
  439. interpreted as a filename pattern to be globbed, and either an array of
  440. filenames or the next filename in the list is returned, depending on
  441. context.  One level of `$' interpretation is done first, but you can't
  442. say `<$foo>' because that's an indirect filehandle as explained in the
  443. previous paragraph.  You could insert curly brackets to force
  444. interpretation as a filename glob: `<${foo}>'.  Example:
  445.  
  446.      while (<*.c>) {
  447.              chmod 0644, $_;
  448.      }
  449.  
  450. is equivalent to
  451.  
  452.      open(foo, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  453.      while (<foo>) {
  454.              chop;
  455.              chmod 0644, $_;
  456.      }
  457.  
  458.    In fact, it's currently implemented that way.  (Which means it will
  459. not work on filenames with spaces in them unless you have `/bin/csh' on
  460. your machine.)  Of course, the shortest way to do the above is:
  461.  
  462.      chmod 0644, <*.c>;
  463.  
  464. 
  465. File: perl.info,  Node: Syntax,  Next: Compound Statements,  Prev: Data Types,  Up: Top
  466.  
  467. Syntax
  468. ******
  469.  
  470.    A *perl* script consists of a sequence of declarations and commands.
  471. The only things that need to be declared in *perl* are report formats
  472. and subroutines.  See the sections below for more information on those
  473. declarations.  All uninitialized user-created objects are assumed to
  474. start with a null or 0 value until they are defined by some explicit
  475. operation such as assignment.  The sequence of commands is executed
  476. just once, unlike in `sed' and `awk' scripts, where the sequence of
  477. commands is executed for each input line.  While this means that you
  478. must explicitly loop over the lines of your input file (or files), it
  479. also means you have much more control over which files and which lines
  480. you look at.  (Actually, I'm lying--it is possible to do an implicit
  481. loop with either the `-n' or `-p' switch.)
  482.  
  483.    A declaration can be put anywhere a command can, but has no effect on
  484. the execution of the primary sequence of commands--declarations all
  485. take effect at compile time.  Typically all the declarations are put at
  486. the beginning or the end of the script.
  487.  
  488.    *Perl* is, for the most part, a free-form language.  (The only
  489. exception to this is format declarations, for fairly obvious reasons.)
  490. Comments are indicated by the `#' character, and extend to the end of
  491. the line.  If you attempt to use `/* */' C comments, it will be
  492. interpreted either as division or pattern matching, depending on the
  493. context.  So don't do that.
  494.  
  495. 
  496. File: perl.info,  Node: Compound Statements,  Next: Simple Statements,  Prev: Syntax,  Up: Top
  497.  
  498. Compound Statements
  499. *******************
  500.  
  501.    In *perl*, a sequence of commands may be treated as one command by
  502. enclosing it in curly brackets.  We will call this a BLOCK.
  503.  
  504. The following compound commands may be used to control flow:
  505.  
  506.      if (EXPR) BLOCK
  507.      if (EXPR) BLOCK else BLOCK
  508.      if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  509.      LABEL while (EXPR) BLOCK
  510.      LABEL while (EXPR) BLOCK continue BLOCK
  511.      LABEL for (EXPR; EXPR; EXPR) BLOCK
  512.      LABEL foreach VAR (ARRAY) BLOCK
  513.      LABEL BLOCK continue BLOCK
  514.  
  515.    Note that, unlike C and Pascal, these are defined in terms of BLOCKs,
  516. not statements.  This means that the curly brackets are *required*--no
  517. dangling statements allowed.  If you want to write conditionals without
  518. curly brackets there are several other ways to do it.  The following
  519. all do the same thing:
  520.  
  521.      if (!open(foo)) { die "Can't open $foo: $!"; }
  522.      die "Can't open $foo: $!" unless open(foo);
  523.      open(foo) || die "Can't open $foo: $!"; # foo or bust!
  524.      open(foo) ? 'hi mom' : die "Can't open $foo: $!";
  525.                              # a bit exotic, that last one
  526.  
  527. The `if' statement is straightforward.  Since BLOCKs are always bounded
  528. by curly brackets, there is never any ambiguity about which `if' an
  529. `else' goes with.  If you use `unless' in place of `if', the sense of
  530. the test is reversed.
  531.  
  532.    The `while' statement executes the block as long as the expression
  533. is true (does not evaluate to the null string or 0).  The LABEL is
  534. optional, and if present, consists of an identifier followed by a colon.
  535. The LABEL identifies the loop for the loop control statements `next',
  536. `last', and `redo' (see below).  If there is a `continue' BLOCK, it is
  537. always executed just before the conditional is about to be evaluated
  538. again, similarly to the third part of a `for' loop in C.  Thus it can
  539. be used to increment a loop variable, even when the loop has been
  540. continued via the `next' statement (similar to the C `continue'
  541. statement).
  542.  
  543.    If the word `while' is replaced by the word `until', the sense of
  544. the test is reversed, but the conditional is still tested before the
  545. first iteration.
  546.  
  547.    In either the `if' or the `while' statement, you may replace
  548. `(EXPR)' with a BLOCK, and the conditional is true if the value of the
  549. last command in that block is true.
  550.  
  551. The `for' loop works exactly like the corresponding `while' loop:
  552.  
  553.      for ($i = 1; $i < 10; $i++) {
  554.              ...
  555.      }
  556.  
  557. is the same as
  558.  
  559.      $i = 1;
  560.      while ($i < 10) {
  561.              ...
  562.      } continue {
  563.              $i++;
  564.      }
  565.  
  566.    The `foreach' loop iterates over a normal array value and sets the
  567. variable VAR to be each element of the array in turn.  The variable is
  568. implicitly local to the loop, and regains its former value upon exiting
  569. the loop.  The `foreach' keyword is actually identical to the `for'
  570. keyword, so you can use `foreach' for readability or `for' for brevity.
  571. If VAR is omitted, `$_' is set to each value.  If ARRAY is an actual
  572. array (as opposed to an expression returning an array value), you can
  573. modify each element of the array by modifying VAR inside the loop.
  574. Examples:
  575.  
  576.      for (@ary) { s/foo/bar/; }
  577.      
  578.      foreach $elem (@elements) {
  579.              $elem *= 2;
  580.      }
  581.      
  582.      for ((10,9,8,7,6,5,4,3,2,1,'BOOM')) {
  583.              print $_, "\n"; sleep(1);
  584.      }
  585.      
  586.      for (1..15) { print "Merry Christmas\n"; }
  587.      
  588.      foreach $item (split(/:[\\\n:]*/, $ENV{'TERMCAP'})) {
  589.              print "Item: $item\n";
  590.      }
  591.  
  592.    The BLOCK by itself (labeled or not) is equivalent to a loop that
  593. executes once.  Thus you can use any of the loop control statements in
  594. it to leave or restart the block.  The `continue' block is optional.
  595. This construct is particularly nice for doing case structures.
  596.  
  597.      foo: {
  598.              if (/^abc/) { $abc = 1; last foo; };
  599.              if (/^def/) { $def = 1; last foo; };
  600.              if (/^xyz/) { $xyz = 1; last foo; };
  601.              $nothing = 1;
  602.      }
  603.  
  604.    There is no official switch statement in perl, because there are
  605. already several ways to write the equivalent.  In addition to the
  606. above, you could write:
  607.  
  608.      foo: {
  609.              $abc = 1, last foo  if /^abc/;
  610.              $def = 1, last foo  if /^def/;
  611.              $xyz = 1, last foo  if /^xyz/;
  612.              $nothing = 1;
  613.      }
  614.  
  615. or
  616.  
  617.      foo: {
  618.              /^abc/ && do { $abc = 1; last foo; }
  619.              /^def/ && do { $def = 1; last foo; }
  620.              /^xyz/ && do { $xyz = 1; last foo; }
  621.              $nothing = 1;
  622.      }
  623.  
  624. or
  625.  
  626.      foo: {
  627.              /^abc/ && ($abc = 1, last foo);
  628.              /^def/ && ($def = 1, last foo);
  629.              /^xyz/ && ($xyz = 1, last foo);
  630.              $nothing = 1;
  631.      }
  632.  
  633. or even
  634.  
  635.      if (/^abc/)
  636.              { $abc = 1; }
  637.      elsif (/^def/)
  638.              { $def = 1; }
  639.      elsif (/^xyz/)
  640.              { $xyz = 1; }
  641.      else
  642.              {$nothing = 1;}
  643.  
  644.    As it happens, these are all optimized internally to a switch
  645. structure, so perl jumps directly to the desired statement, and you
  646. needn't worry about perl executing a lot of unnecessary statements when
  647. you have a string of 50 `elsif's, as long as you are testing the same
  648. simple scalar variable using `==', `eq', or pattern matching as above.
  649. (If you're curious as to whether the optimizer has done this for a
  650. particular case statement, you can use the `-D1024' switch to list the
  651. syntax tree before execution.)
  652.  
  653. 
  654. File: perl.info,  Node: Simple Statements,  Next: Expressions,  Prev: Compound Statements,  Up: Top
  655.  
  656. Simple Statements
  657. *****************
  658.  
  659.    The only kind of simple statement is an expression evaluated for its
  660. side effects.  Every simple statement must be terminated with a
  661. semicolon, unless it is the final statement in a block, in which case
  662. the semicolon is optional.  (Semicolon is still encouraged there if the
  663. block takes up more than one line).
  664.  
  665.    Any simple statement may optionally be followed by a single modifier,
  666. just before the terminating semicolon.  The possible modifiers are:
  667.  
  668.      if EXPR
  669.      unless EXPR
  670.      while EXPR
  671.      until EXPR
  672.  
  673.    The `if' and `unless' modifiers have the expected semantics.  The
  674. `while' and `until' modifiers also have the expected semantics
  675. (conditional evaluated first), except when applied to a do-BLOCK or a
  676. do-SUBROUTINE command, in which case the block executes once before the
  677. conditional is evaluated.  This is so that you can write loops like:
  678.  
  679.      do {
  680.              $_ = <STDIN>;
  681.              ...
  682.      } until $_ eq ".\n";
  683.  
  684. (See the `do' operator below.  Note also that the loop control commands
  685. described later will *NOT* work in this construct, since modifiers
  686. don't take loop labels.  Sorry.)
  687.  
  688. 
  689. File: perl.info,  Node: Expressions,  Next: Commands,  Prev: Simple Statements,  Up: Top
  690.  
  691. Expressions
  692. ***********
  693.  
  694.    Since *perl* expressions work almost exactly like C expressions,
  695. only the differences will be mentioned here.
  696.  
  697. Here's what *perl* has that C doesn't:
  698.  
  699. **
  700.      The exponentiation operator.
  701.  
  702. **=
  703.      The exponentiation assignment operator.
  704.  
  705. ()
  706.      The null list, used to initialize an array to null.
  707.  
  708. .
  709.      Concatenation of two strings.
  710.  
  711. .=
  712.      The concatenation assignment operator.
  713.  
  714. eq
  715.      String equality (`==' is numeric equality).  For a mnemonic just
  716.      think of `eq' as a string.  (If you are used to the `awk' behavior
  717.      of using `==' for either string or numeric equality based on the
  718.      current form of the comparands, beware!  You must be explicit
  719.      here.)
  720.  
  721. ne
  722.      String inequality (`!=' is numeric inequality).
  723.  
  724. lt
  725.      String less than.
  726.  
  727. gt
  728.      String greater than.
  729.  
  730. le
  731.      String less than or equal.
  732.  
  733. ge
  734.      String greater than or equal.
  735.  
  736. cmp
  737.      String comparison, returning -1, 0, or 1.
  738.  
  739. <=>
  740.      Numeric comparison, returning -1, 0, or 1.
  741.  
  742. =~
  743.      Certain operations search or modify the string `$_' by default.
  744.      This operator makes that kind of operation work on some other
  745.      string.  The right argument is a search pattern, substitution, or
  746.      translation.  The left argument is what is supposed to be
  747.      searched, substituted, or translated instead of the default `$_'.
  748.      The return value indicates the success of the operation.  (If the
  749.      right argument is an expression other than a search pattern,
  750.      substitution, or translation, it is interpreted as a search
  751.      pattern at run time.  This is less efficient than an explicit
  752.      search, since the pattern must be compiled every time the
  753.      expression is evaluated.)  The precedence of this operator is lower
  754.      than unary minus and autoincrement/decrement, but higher than
  755.      everything else.
  756.  
  757. !~
  758.      Just like `=~' except the return value is negated.
  759.  
  760. x
  761.      The repetition operator.  Returns a string consisting of the left
  762.      operand repeated the number of times specified by the right
  763.      operand.  In an array context, if the left operand is a list in
  764.      parens, it repeats the list.
  765.  
  766.           print '-' x 80;         # print row of dashes
  767.           print '-' x80;          # illegal, x80 is identifier
  768.           
  769.           print "\t" x ($tab/8), ' ' x ($tab%8);  # tab over
  770.           
  771.           @ones = (1) x 80;      # an array of 80 1's
  772.           @ones = (5) x @ones;  # set all elements to 5
  773.  
  774. x=
  775.      The repetition assignment operator.  Only works on scalars.
  776.  
  777. ..
  778.      The range operator, which is really two different operators
  779.      depending on the context.  In an array context, returns an array
  780.      of values counting (by ones) from the left value to the right
  781.      value.  This is useful for writing `for (1..10)' loops and for
  782.      doing slice operations on arrays.
  783.  
  784.      In a scalar context, `..' returns a boolean value.  The operator is
  785.      bistable, like a flip-flop, and emulates the line-range (comma)
  786.      operator of `sed', `awk', and various editors.  Each `..' operator
  787.      maintains its own boolean state.  It is false as long as its left
  788.      operand is false.  Once the left operand is true, the range
  789.      operator stays true until the right operand is true, *AFTER* which
  790.      the range operator becomes false again.  (It doesn't become false
  791.      till the next time the range operator is evaluated.  It can test
  792.      the right operand and become false on the same evaluation it
  793.      became true (as in `awk'), but it still returns true once.  If you
  794.      don't want it to test the right operand till the next evaluation
  795.      (as in `sed'), use three dots (...) instead of two.) The right
  796.      operand is not evaluated while the operator is in the "false"
  797.      state, and the left operand is not evaluated while the operator is
  798.      in the "true" state.  The precedence is a little lower than `||'
  799.      and `&&'.  The value returned is either the null string for false,
  800.      or a sequence number (beginning with 1) for true.  The sequence
  801.      number is reset for each range encountered.  The final sequence
  802.      number in a range has the string `E0' appended to it, which
  803.      doesn't affect its numeric value, but gives you something to
  804.      search for if you want to exclude the endpoint.  You can exclude
  805.      the beginning point by waiting for the sequence number to be
  806.      greater than 1.  If either operand of scalar `..' is static, that
  807.      operand is implicitly compared to the `$.' variable, the current
  808.      line number.  Examples:
  809.  
  810.      As a scalar operator:
  811.           if (101 .. 200) { print; }        # print 2nd hundred lines
  812.           
  813.           next line if (1 .. /^$/);   # skip header lines
  814.           
  815.           s/^/> / if (/^$/ .. eof()); # quote body
  816.  
  817.      As an array operator:
  818.           for (101 .. 200) { print; } # print $_ 100 times
  819.           
  820.           @foo = @foo[$[ .. $#foo]; # an expensive no-op
  821.           @foo = @foo[$#foo-4 .. $#foo];    # slice last 5 items
  822.  
  823. -x
  824.      A file test.  This unary operator takes one argument, either a
  825.      filename or a filehandle, and tests the associated file to see if
  826.      something is true about it.  If the argument is omitted, tests
  827.      `$_', except for `-t', which tests `STDIN'.  It returns 1 for true
  828.      and '' for false, or the undefined value if the file doesn't
  829.      exist.  Precedence is higher than logical and relational
  830.      operators, but lower than arithmetic operators.  The operator may
  831.      be any of:
  832.  
  833.           -r      File is readable by effective uid/gid.
  834.           -w      File is writable by effective uid/gid.
  835.           -x      File is executable by effective uid/gid.
  836.           -o      File is owned by effective uid.
  837.           -R      File is readable by real uid/gid.
  838.           -W      File is writable by real uid/gid.
  839.           -X      File is executable by real uid/gid.
  840.           -O      File is owned by real uid.
  841.           -e      File exists.
  842.           -z      File has zero size.
  843.           -s      File has non-zero size (returns size).
  844.           -f      File is a plain file.
  845.           -d      File is a directory.
  846.           -l      File is a symbolic link.
  847.           -p      File is a named pipe (FIFO).
  848.           -S      File is a socket.
  849.           -b      File is a block special file.
  850.           -c      File is a character special file.
  851.           -u      File has setuid bit set.
  852.           -g      File has setgid bit set.
  853.           -k      File has sticky bit set.
  854.           -t      Filehandle is opened to a tty.
  855.           -T      File is a text file.
  856.           -B      File is a binary file (opposite of -T).
  857.           -M      Age of file in days when script started.
  858.           -A      Same for access time.
  859.           -C      Same for inode change time.
  860.  
  861.      The interpretation of the file permission operators `-r', `-R',
  862.      `-w', `-W', `-x' and `-X' is based solely on the mode of the file
  863.      and the uids and gids of the user.  There may be other reasons you
  864.      can't actually read, write or execute the file.  Also note that,
  865.      for the superuser, `-r', `-R', `-w' and `-W' always return 1, and
  866.      `-x' and `-X' return 1 if any execute bit is set in the mode.
  867.      Scripts run by the superuser may thus need to do a `stat()' in
  868.      order to determine the actual mode of the file, or temporarily set
  869.      the uid to something else.
  870.  
  871.      Example:
  872.  
  873.           while (<>) {
  874.                   chop;
  875.                   next unless -f $_;      # ignore specials
  876.                   ...
  877.           }
  878.  
  879.      Note that `-s/a/b/' does not do a negated substitution.  Saying
  880.      `-exp($foo)' still works as expected, however--only single letters
  881.      following a minus are interpreted as file tests.
  882.  
  883.      The `-T' and `-B' switches work as follows.  The first block or so
  884.      of the file is examined for odd characters such as strange control
  885.      codes or metacharacters.  If too many odd characters (>10%) are
  886.      found, it's a `-B' file, otherwise it's a `-T' file.  Also, any
  887.      file containing null in the first block is considered a binary
  888.      file.  If `-T' or `-B' is used on a filehandle, the current stdio
  889.      buffer is examined rather than the first block.  Both `-T' and `-B'
  890.      return TRUE on a null file, or a file at EOF when testing a
  891.      filehandle.
  892.  
  893.      If any of the file tests (or either `stat' operator) are given the
  894.      special filehandle consisting of a solitary underline `_', then the
  895.      stat structure of the previous file test (or `stat' operator) is
  896.      used, saving a system call.  (This doesn't work with `-t', and you
  897.      need to remember that `lstat' and `-l' will leave values in the
  898.      stat structure for the symbolic link, not the real file.)  Example:
  899.  
  900.           print "Can do.\n" if -r $a || -w _ || -x _;
  901.           
  902.           stat($filename);
  903.           print "Readable\n" if -r _;
  904.           print "Writable\n" if -w _;
  905.           print "Executable\n" if -x _;
  906.           print "Setuid\n" if -u _;
  907.           print "Setgid\n" if -g _;
  908.           print "Sticky\n" if -k _;
  909.           print "Text\n" if -T _;
  910.           print "Binary\n" if -B _;
  911.  
  912. Here is what C has that *perl* doesn't:
  913.  
  914. unary &
  915.      Address-of operator.
  916.  
  917. unary *
  918.      Dereference-address operator.
  919.  
  920. (TYPE)
  921.      Type casting operator.
  922.  
  923.    Like C, *perl* does a certain amount of expression evaluation at
  924. compile time, whenever it determines that all of the arguments to an
  925. operator are static and have no side effects.  In particular, string
  926. concatenation happens at compile time between literals that don't do
  927. variable substitution.  Backslash interpretation also happens at compile
  928. time.  You can say:
  929.  
  930.      'Now is the time for all' . "\n" .
  931.      'good men to come to.'
  932.  
  933. and this all reduces to one string internally.
  934.  
  935.    The autoincrement operator has a little extra built-in magic to it.
  936. If you increment a variable that is numeric, or that has ever been used
  937. in a numeric context, you get a normal increment.  If, however, the
  938. variable has only been used in string contexts since it was set, and has
  939. a value that is not null and matches the pattern `/^[a-zA-Z]*[0-9]*$/',
  940. the increment is done as a string, preserving each character within its
  941. range, with carry:
  942.  
  943.      print ++($foo = '99');  # prints `100'
  944.      print ++($foo = 'a0');  # prints `a1'
  945.      print ++($foo = 'Az');  # prints `Ba'
  946.      print ++($foo = 'zz');  # prints `aaa'
  947.  
  948. The autodecrement is not magical.
  949.  
  950.    The range operator (in an array context) makes use of the magical
  951. autoincrement algorithm if the minimum and maximum are strings.  You can
  952. say
  953.  
  954.      @alphabet = ('A' .. 'Z');
  955.  
  956. to get all the letters of the alphabet, or
  957.  
  958.      $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  959.  
  960. to get a hexadecimal digit, or
  961.  
  962.      @z2 = ('01' .. '31');  print @z2[$mday];
  963.  
  964. to get dates with leading zeros.  (If the final value specified is not
  965. in the sequence that the magical increment would produce, the sequence
  966. goes until the next value would be longer than the final value
  967. specified.)
  968.  
  969.    The `||' and `&&' operators differ from C's in that, rather than
  970. returning 0 or 1, they return the last value evaluated.  Thus, a
  971. portable way to find out the home directory might be:
  972.  
  973.      $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  974.          (getpwuid($<))[7] || die "You're homeless!\en";
  975.  
  976.    Along with the literals and variables mentioned earlier, the
  977. operations in the following section can serve as terms in an
  978. expression.  Some of these operations take a LIST as an argument.  Such
  979. a list can consist of any combination of scalar arguments or array
  980. values; the array values will be included in the list as if each
  981. individual element were interpolated at that point in the list, forming
  982. a longer single-dimensional array value.  Elements of the LIST should be
  983. separated by commas.  If an operation is listed both with and without
  984. parentheses around its arguments, it means you can either use it as a
  985. unary operator or as a function call.  To use it as a function call, the
  986. next token on the same line must be a left parenthesis.  (There may be
  987. intervening white space.)  Such a function then has highest precedence,
  988. as you would expect from a function.  If any token other than a left
  989. parenthesis follows, then it is a unary operator, with a precedence
  990. depending only on whether it is a LIST operator or not.  LIST operators
  991. have lowest precedence.  All other unary operators have a precedence
  992. greater than relational operators but less than arithmetic operators.
  993. *Note Precedence::, for more info.
  994.  
  995.    For operators that can be used in either a scalar or array context,
  996. failure is generally indicated in a scalar context by returning the
  997. undefined value, and in an array context by returning the null list.
  998. Remember though that *THERE IS NO GENERAL RULE FOR CONVERTING A LIST
  999. INTO A SCALAR.* Each operator decides which sort of scalar it would be
  1000. most appropriate to return.  Some operators return the length of the
  1001. list that would have been returned in an array context.  Some operators
  1002. return the first value in the list.  Some operators return the last
  1003. value in the list.  Some operators return a count of successful
  1004. operations.  In general, they do what you want, unless you want
  1005. consistency.
  1006.  
  1007. 
  1008. File: perl.info,  Node: Commands,  Next: Precedence,  Prev: Expressions,  Up: Top
  1009.  
  1010. Commands
  1011. ********
  1012.  
  1013. * Menu:
  1014.  
  1015. * Math Functions::                Various trigonometric and math functions.
  1016. * Structure Conversion::          How to convert binary structures.
  1017. * String Functions::              Functions to interact with strings.
  1018. * Array and List Functions::      Functions that manipulate arrays/lists.
  1019. * File Operations::               Functions that operate on files.
  1020. * Directory Reading Functions::   Functions for reading directories.  :-)
  1021. * Input/Output::                  Printing and reading data.
  1022. * Search and Replace Functions::  Pattern matching functions.
  1023. * System Interaction::            A mix of functions dealing with the system.
  1024. * Networking Functions::          Interprocess Communication Functions.
  1025. * System V IPC::                  System V IPC Functions.
  1026. * Time Functions::                Time related functions.
  1027. * DBM Functions::                 Functions for accessing `dbm' files.
  1028. * Flow Control Functions::        Functions related to flow control.
  1029. * Perl Library Functions::        How to include perl libraries.
  1030. * Subroutine Functions::          Functions related to user-defined subs.
  1031. * Variable Functions::            Functions dealing with variables.
  1032.                                     (not already mentioned)
  1033. * Miscellaneous Functions::       A catch-all for all other functions.  ;-)
  1034.  
  1035. 
  1036. File: perl.info,  Node: Math Functions,  Next: Structure Conversion,  Up: Commands
  1037.  
  1038. Math Functions
  1039. ==============
  1040.  
  1041. atan2(Y,X)
  1042.      Returns the arctangent of Y/X in the range -PI to PI.
  1043.  
  1044. cos(EXPR)
  1045. cos EXPR
  1046. cos
  1047.      Returns the cosine of EXPR (expressed in radians).  If EXPR is
  1048.      omitted takes cosine of `$_'.
  1049.  
  1050. exp(EXPR)
  1051. exp EXPR
  1052. exp
  1053.      Returns `e' to the power of EXPR.  If EXPR is omitted, gives
  1054.      `exp($_)'.
  1055.  
  1056. hex(EXPR)
  1057. hex EXPR
  1058. hex
  1059.      Returns the decimal value of EXPR interpreted as an hex string.
  1060.      (To interpret strings that might start with `0' or `0x' see
  1061.      `oct()'.)  If EXPR is omitted, uses `$_'.
  1062.  
  1063. int(EXPR)
  1064. int EXPR
  1065. int
  1066.      Returns the integer portion of EXPR.  If EXPR is omitted, uses
  1067.      `$_'.
  1068.  
  1069. log(EXPR)
  1070. log EXPR
  1071. log
  1072.      Returns logarithm (base `e') of EXPR.  If EXPR is omitted, returns
  1073.      log of `$_'.
  1074.  
  1075. oct(EXPR)
  1076. oct EXPR
  1077. oct
  1078.      Returns the decimal value of EXPR interpreted as an octal string.
  1079.      (If EXPR happens to start off with `0x', interprets it as a hex
  1080.      string instead.)  The following will handle decimal, octal and hex
  1081.      in the standard notation:
  1082.  
  1083.           $val = oct($val) if $val =~ /^0/;
  1084.  
  1085.      If EXPR is omitted, uses `$_'.
  1086.  
  1087. sin(EXPR)
  1088. sin EXPR
  1089. sin
  1090.      Returns the sine of EXPR (expressed in radians).  If EXPR is
  1091.      omitted, returns sine of `$_'.
  1092.  
  1093. sqrt(EXPR)
  1094. sqrt EXPR
  1095. sqrt
  1096.      Return the square root of EXPR.  If EXPR is omitted, returns
  1097.      square root of `$_'.
  1098.  
  1099. 
  1100. File: perl.info,  Node: Structure Conversion,  Next: String Functions,  Prev: Math Functions,  Up: Commands
  1101.  
  1102. Structure Conversion
  1103. ====================
  1104.  
  1105. pack(TEMPLATE,LIST)
  1106.      Takes an array or list of values and packs it into a binary
  1107.      structure, returning the string containing the structure.  The
  1108.      TEMPLATE is a sequence of characters that give the order and type
  1109.      of values, as follows:
  1110.  
  1111.           A       An ascii string, will be space padded.
  1112.           a       An ascii string, will be null padded.
  1113.           c       A signed char value.
  1114.           C       An unsigned char value.
  1115.           s       A signed short value.
  1116.           S       An unsigned short value.
  1117.           i       A signed integer value.
  1118.           I       An unsigned integer value.
  1119.           l       A signed long value.
  1120.           L       An unsigned long value.
  1121.           n       A short in `network' order.
  1122.           N       A long in `network' order.
  1123.           f       A single-precision float in the native format.
  1124.           d       A double-precision float in the native format.
  1125.           p       A pointer to a string.
  1126.           v       A short in `VAX' (little-endian) order.
  1127.           V       A long in `VAX' (little-endian) order.
  1128.           x       A null byte.
  1129.           X       Back up a byte.
  1130.           @       Null fill to absolute position.
  1131.           u       A uuencoded string.
  1132.           b       A bit string (ascending bit order, like vec()).
  1133.           B       A bit string (descending bit order).
  1134.           h       A hex string (low nybble first).
  1135.           H       A hex string (high nybble first).
  1136.  
  1137.      Each letter may optionally be followed by a number which gives a
  1138.      repeat count.  With all types except `a', `A', `b', `B', `h', and
  1139.      `H', the pack function will gobble up that many values from the
  1140.      LIST.  A `*' for the repeat count means to use however many items
  1141.      are left.  The `a' and `A' types gobble just one value, but pack
  1142.      it as a string of length count, padding with nulls or spaces as
  1143.      necessary.  (When unpacking, `A' strips trailing spaces and nulls,
  1144.      but `a' does not.)  Likewise, the `b' and `B' fields pack a string
  1145.      that many bits long.  The `h' and `H' fields pack a string that
  1146.      many nybbles long.  Real numbers (floats and doubles) are in the
  1147.      native machine format only; due to the multiplicity of floating
  1148.      formats around, and the lack of a standard "network"
  1149.      representation, no facility for interchange has been made.  This
  1150.      means that packed floating point data written on one machine may
  1151.      not be readable on another - even if both use IEEE floating point
  1152.      arithmetic (as the endian-ness of the memory representation is not
  1153.      part of the IEEE spec).  Note that perl uses doubles internally
  1154.      for all numeric calculation, and converting from double to float
  1155.      back to double will lose precision (i.e. `unpack("f", pack("f",
  1156.      $foo))' will not in general equal `$foo').
  1157.  
  1158.      Examples:
  1159.  
  1160.           $foo = pack("cccc",65,66,67,68);
  1161.           # foo eq "ABCD"
  1162.           $foo = pack("c4",65,66,67,68);
  1163.           # same thing
  1164.           
  1165.           $foo = pack("ccxxcc",65,66,67,68);
  1166.           # foo eq "AB\0\0CD"
  1167.           
  1168.           $foo = pack("s2",1,2);
  1169.           # "\1\0\2\0" on little-endian
  1170.           # "\0\1\0\2" on big-endian
  1171.           
  1172.           $foo = pack("a4","abcd","x","y","z");
  1173.           # "abcd"
  1174.           
  1175.           $foo = pack("aaaa","abcd","x","y","z");
  1176.           # "axyz"
  1177.           
  1178.           $foo = pack("a14","abcdefg");
  1179.           # "abcdefg\0\0\0\0\0\0\0"
  1180.           
  1181.           $foo = pack("i9pl", gmtime);
  1182.           # a real struct tm (on my system anyway)
  1183.           
  1184.           sub bintodec {
  1185.               unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  1186.           }
  1187.  
  1188.      The same template may generally also be used in the `unpack'
  1189.      function.
  1190.  
  1191. unpack(TEMPLATE,EXPR)
  1192.      `unpack' does the reverse of `pack': it takes a string
  1193.      representing a structure and expands it out into an array value,
  1194.      returning the array value.  (In a scalar context, it merely
  1195.      returns the first value produced.)  The TEMPLATE has the same
  1196.      format as in the `pack' function.  Here's a subroutine that does
  1197.      substring:
  1198.  
  1199.           sub substr {
  1200.                   local($what,$where,$howmuch) = @_;
  1201.                   unpack("x$where a$howmuch", $what);
  1202.           }
  1203.  
  1204.      and then there's
  1205.  
  1206.           sub ord { unpack("c",$_[0]); }
  1207.  
  1208.      In addition, you may prefix a field with a `%<number>' to indicate
  1209.      that you want a <number>-bit checksum of the items instead of the
  1210.      items themselves.  Default is a 16-bit checksum.  For example, the
  1211.      following computes the same number as the System V sum program:
  1212.  
  1213.           while (<>) {
  1214.               $checksum += unpack("%16C*", $_);
  1215.           }
  1216.           $checksum %= 65536;
  1217.  
  1218.