home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl501m.zip / pod / perlfunc.pod < prev    next >
Text File  |  1995-03-16  |  100KB  |  2,953 lines

  1. =head1 NAME
  2.  
  3. perlfunc - Perl builtin functions
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. The functions in this section can serve as terms in an expression.
  8. They fall into two major categories: list operators and named unary
  9. operators.  These differ in their precedence relationship with a
  10. following comma.  (See the precedence table in L<perlop>.)  List
  11. operators take more than one argument, while unary operators can never
  12. take more than one argument.  Thus, a comma terminates the argument of
  13. a unary operator, but merely separates the arguments of a list
  14. operator.  A unary operator generally provides a scalar context to its
  15. argument, while a list operator may provide either scalar and list
  16. contexts for its arguments.  If it does both, the scalar arguments will
  17. be first, and the list argument will follow.  (Note that there can only
  18. ever be one list argument.)  For instance, splice() has three scalar
  19. arguments followed by a list.
  20.  
  21. In the syntax descriptions that follow, list operators that expect a
  22. list (and provide list context for the elements of the list) are shown
  23. with LIST as an argument.  Such a list may consist of any combination
  24. of scalar arguments or list values; the list values will be included
  25. in the list as if each individual element were interpolated at that
  26. point in the list, forming a longer single-dimensional list value.
  27. Elements of the LIST should be separated by commas.
  28.  
  29. Any function in the list below may be used either with or without
  30. parentheses around its arguments.  (The syntax descriptions omit the
  31. parens.)  If you use the parens, the simple (but occasionally
  32. surprising) rule is this: It I<LOOKS> like a function, therefore it I<IS> a
  33. function, and precedence doesn't matter.  Otherwise it's a list
  34. operator or unary operator, and precedence does matter.  And whitespace
  35. between the function and left parenthesis doesn't count--so you need to
  36. be careful sometimes:
  37.  
  38.     print 1+2+3;    # Prints 6.
  39.     print(1+2) + 3;    # Prints 3.
  40.     print (1+2)+3;    # Also prints 3!
  41.     print +(1+2)+3;    # Prints 6.
  42.     print ((1+2)+3);    # Prints 6.
  43.  
  44. If you run Perl with the B<-w> switch it can warn you about this.  For
  45. example, the third line above produces:
  46.  
  47.     print (...) interpreted as function at - line 1.
  48.     Useless use of integer addition in void context at - line 1.
  49.  
  50. For functions that can be used in either a scalar or list context,
  51. non-abortive failure is generally indicated in a scalar context by
  52. returning the undefined value, and in a list context by returning the
  53. null list.
  54.  
  55. Remember the following rule:
  56.  
  57. =over 5
  58.  
  59. =item *
  60.  
  61. I<THERE IS NO GENERAL RULE FOR CONVERTING A LIST INTO A SCALAR!>
  62.  
  63. =back
  64.  
  65. Each operator and function decides which sort of value it would be most
  66. appropriate to return in a scalar context.  Some operators return the
  67. length of the list that would have been returned in a list context.  Some
  68. operators return the first value in the list.  Some operators return the
  69. last value in the list.  Some operators return a count of successful
  70. operations.  In general, they do what you want, unless you want
  71. consistency.
  72.  
  73. =over 8
  74.  
  75. =item -X FILEHANDLE
  76.  
  77. =item -X EXPR
  78.  
  79. =item -X
  80.  
  81. A file test, where X is one of the letters listed below.  This unary
  82. operator takes one argument, either a filename or a filehandle, and
  83. tests the associated file to see if something is true about it.  If the
  84. argument is omitted, tests $_, except for C<-t>, which tests STDIN.
  85. Unless otherwise documented, it returns C<1> for TRUE and C<''> for FALSE, or
  86. the undefined value if the file doesn't exist.  Despite the funny
  87. names, precedence is the same as any other named unary operator, and
  88. the argument may be parenthesized like any other unary operator.  The
  89. operator may be any of:
  90.  
  91.     -r    File is readable by effective uid/gid.
  92.     -w    File is writable by effective uid/gid.
  93.     -x    File is executable by effective uid/gid.
  94.     -o    File is owned by effective uid.
  95.  
  96.     -R    File is readable by real uid/gid.
  97.     -W    File is writable by real uid/gid.
  98.     -X    File is executable by real uid/gid.
  99.     -O    File is owned by real uid.
  100.  
  101.     -e    File exists.
  102.     -z    File has zero size.
  103.     -s    File has non-zero size (returns size).
  104.  
  105.     -f    File is a plain file.
  106.     -d    File is a directory.
  107.     -l    File is a symbolic link.
  108.     -p    File is a named pipe (FIFO).
  109.     -S    File is a socket.
  110.     -b    File is a block special file.
  111.     -c    File is a character special file.
  112.     -t    Filehandle is opened to a tty.
  113.  
  114.     -u    File has setuid bit set.
  115.     -g    File has setgid bit set.
  116.     -k    File has sticky bit set.
  117.  
  118.     -T    File is a text file.
  119.     -B    File is a binary file (opposite of -T).
  120.  
  121.     -M    Age of file in days when script started.
  122.     -A    Same for access time.
  123.     -C    Same for inode change time.
  124.  
  125. The interpretation of the file permission operators C<-r>, C<-R>, C<-w>,
  126. C<-W>, C<-x> and C<-X> is based solely on the mode of the file and the
  127. uids and gids of the user.  There may be other reasons you can't actually
  128. read, write or execute the file.  Also note that, for the superuser,
  129. C<-r>, C<-R>, C<-w> and C<-W> always return 1, and C<-x> and C<-X> return
  130. 1 if any execute bit is set in the mode.  Scripts run by the superuser may
  131. thus need to do a stat() in order to determine the actual mode of the
  132. file, or temporarily set the uid to something else.
  133.  
  134. Example:
  135.  
  136.     while (<>) {
  137.     chop;
  138.     next unless -f $_;    # ignore specials
  139.     ...
  140.     }
  141.  
  142. Note that C<-s/a/b/> does not do a negated substitution.  Saying
  143. C<-exp($foo)> still works as expected, however--only single letters
  144. following a minus are interpreted as file tests.
  145.  
  146. The C<-T> and C<-B> switches work as follows.  The first block or so of the
  147. file is examined for odd characters such as strange control codes or
  148. characters with the high bit set.  If too many odd characters (>30%)
  149. are found, it's a C<-B> file, otherwise it's a C<-T> file.  Also, any file
  150. containing null in the first block is considered a binary file.  If C<-T>
  151. or C<-B> is used on a filehandle, the current stdio buffer is examined
  152. rather than the first block.  Both C<-T> and C<-B> return TRUE on a null
  153. file, or a file at EOF when testing a filehandle.
  154.  
  155. If any of the file tests (or either the stat() or lstat() operators) are given the
  156. special filehandle consisting of a solitary underline, then the stat
  157. structure of the previous file test (or stat operator) is used, saving
  158. a system call.  (This doesn't work with C<-t>, and you need to remember
  159. that lstat() and C<-l> will leave values in the stat structure for the
  160. symbolic link, not the real file.)  Example:
  161.  
  162.     print "Can do.\n" if -r $a || -w _ || -x _;
  163.  
  164.     stat($filename);
  165.     print "Readable\n" if -r _;
  166.     print "Writable\n" if -w _;
  167.     print "Executable\n" if -x _;
  168.     print "Setuid\n" if -u _;
  169.     print "Setgid\n" if -g _;
  170.     print "Sticky\n" if -k _;
  171.     print "Text\n" if -T _;
  172.     print "Binary\n" if -B _;
  173.  
  174. =item abs VALUE
  175.  
  176. Returns the absolute value of its argument.
  177.  
  178. =item accept NEWSOCKET,GENERICSOCKET
  179.  
  180. Accepts an incoming socket connect, just as the accept(2) system call
  181. does.  Returns the packed address if it succeeded, FALSE otherwise.
  182. See example in L<perlipc>.
  183.  
  184. =item alarm SECONDS
  185.  
  186. Arranges to have a SIGALRM delivered to this process after the
  187. specified number of seconds have elapsed.  (On some machines,
  188. unfortunately, the elapsed time may be up to one second less than you
  189. specified because of how seconds are counted.)  Only one timer may be
  190. counting at once.  Each call disables the previous timer, and an
  191. argument of 0 may be supplied to cancel the previous timer without
  192. starting a new one.  The returned value is the amount of time remaining
  193. on the previous timer.
  194.  
  195. For sleeps of finer granularity than one second, you may use Perl's
  196. syscall() interface to access setitimer(2) if your system supports it, 
  197. or else see L</select()> below.
  198.  
  199. =item atan2 Y,X
  200.  
  201. Returns the arctangent of Y/X in the range -PI to PI.
  202.  
  203. =item bind SOCKET,NAME
  204.  
  205. Binds a network address to a socket, just as the bind system call
  206. does.  Returns TRUE if it succeeded, FALSE otherwise.  NAME should be a
  207. packed address of the appropriate type for the socket.  See example in
  208. L<perlipc>.
  209.  
  210. =item binmode FILEHANDLE
  211.  
  212. Arranges for the file to be read or written in "binary" mode in
  213. operating systems that distinguish between binary and text files.
  214. Files that are not in binary mode have CR LF sequences translated to LF
  215. on input and LF translated to CR LF on output.  Binmode has no effect
  216. under Unix; in DOS, it may be imperative.  If FILEHANDLE is an expression,
  217. the value is taken as the name of the filehandle.
  218.  
  219. =item bless REF,PACKAGE
  220.  
  221. =item bless REF
  222.  
  223. This function tells the referenced object (passed as REF) that it is now
  224. an object in PACKAGE--or the current package if no PACKAGE is specified,
  225. which is the usual case.  It returns the reference for convenience, since
  226. a bless() is often the last thing in a constructor.  See L<perlobj> for
  227. more about the blessing (and blessings) of objects.
  228.  
  229. =item caller EXPR
  230.  
  231. =item caller
  232.  
  233. Returns the context of the current subroutine call.  In a scalar context,
  234. returns TRUE if there is a caller, that is, if we're in a subroutine or
  235. eval() or require(), and FALSE otherwise.  In a list context, returns
  236.  
  237.     ($package, $filename, $line) = caller;
  238.  
  239. With EXPR, it returns some extra information that the debugger uses to
  240. print a stack trace.  The value of EXPR indicates how many call frames
  241. to go back before the current one.
  242.  
  243.     ($package, $filename, $line,
  244.      $subroutine, $hasargs, $wantargs) = caller($i);
  245.  
  246. Furthermore, when called from within the DB package, caller returns more
  247. detailed information: it sets sets the list variable @DB:args to be the
  248. arguments with which that subroutine was invoked.
  249.  
  250. =item chdir EXPR
  251.  
  252. Changes the working directory to EXPR, if possible.  If EXPR is
  253. omitted, changes to home directory.  Returns TRUE upon success, FALSE
  254. otherwise.  See example under die().
  255.  
  256. =item chmod LIST
  257.  
  258. Changes the permissions of a list of files.  The first element of the
  259. list must be the numerical mode.  Returns the number of files
  260. successfully changed.
  261.  
  262.     $cnt = chmod 0755, 'foo', 'bar';
  263.     chmod 0755, @executables;
  264.  
  265. =item chomp VARIABLE
  266.  
  267. =item chomp LIST
  268.  
  269. =item chomp
  270.  
  271. This is a slightly safer version of chop (see below).  It removes any
  272. line ending that corresponds to the current value of C<$/> (also known as
  273. $INPUT_RECORD_SEPARATOR in the C<English> module).  It returns the number
  274. of characters removed.  It's often used to remove the newline from the
  275. end of an input record when you're worried that the final record may be
  276. missing its newline.  When in paragraph mode (C<$/ = "">), it removes all
  277. trailing newlines from the string.  If VARIABLE is omitted, it chomps
  278. $_.  Example:
  279.  
  280.     while (<>) {
  281.     chomp;    # avoid \n on last field
  282.     @array = split(/:/);
  283.     ...
  284.     }
  285.  
  286. You can actually chomp anything that's an lvalue, including an assignment:
  287.  
  288.     chomp($cwd = `pwd`);
  289.     chomp($answer = <STDIN>);
  290.  
  291. If you chomp a list, each element is chomped, and the total number of
  292. characters removed is returned.
  293.  
  294. =item chop VARIABLE
  295.  
  296. =item chop LIST
  297.  
  298. =item chop
  299.  
  300. Chops off the last character of a string and returns the character
  301. chopped.  It's used primarily to remove the newline from the end of an
  302. input record, but is much more efficient than C<s/\n//> because it neither
  303. scans nor copies the string.  If VARIABLE is omitted, chops $_.
  304. Example:
  305.  
  306.     while (<>) {
  307.     chop;    # avoid \n on last field
  308.     @array = split(/:/);
  309.     ...
  310.     }
  311.  
  312. You can actually chop anything that's an lvalue, including an assignment:
  313.  
  314.     chop($cwd = `pwd`);
  315.     chop($answer = <STDIN>);
  316.  
  317. If you chop a list, each element is chopped.  Only the value of the
  318. last chop is returned.
  319.  
  320. Note that chop returns the last character.  To return all but the last
  321. character, use C<substr($string, 0, -1)>.
  322.  
  323. =item chown LIST
  324.  
  325. Changes the owner (and group) of a list of files.  The first two
  326. elements of the list must be the I<NUMERICAL> uid and gid, in that order.
  327. Returns the number of files successfully changed.
  328.  
  329.     $cnt = chown $uid, $gid, 'foo', 'bar';
  330.     chown $uid, $gid, @filenames;
  331.  
  332. Here's an example that looks up non-numeric uids in the passwd file:
  333.  
  334.     print "User: ";
  335.     chop($user = <STDIN>);
  336.     print "Files: "
  337.     chop($pattern = <STDIN>);
  338.  
  339.     ($login,$pass,$uid,$gid) = getpwnam($user)
  340.     or die "$user not in passwd file";
  341.  
  342.     @ary = <${pattern}>;    # expand filenames
  343.     chown $uid, $gid, @ary;
  344.  
  345. =item chr NUMBER
  346.  
  347. Returns the character represented by that NUMBER in the character set.
  348. For example, C<chr(65)> is "A" in ASCII.
  349.  
  350. =item chroot FILENAME
  351.  
  352. Does the same as the system call of that name.  If you don't know what
  353. it does, don't worry about it.  If FILENAME is omitted, does chroot to
  354. $_.
  355.  
  356. =item close FILEHANDLE
  357.  
  358. Closes the file or pipe associated with the file handle, returning TRUE
  359. only if stdio successfully flushes buffers and closes the system file
  360. descriptor.  You don't have to close FILEHANDLE if you are immediately
  361. going to do another open on it, since open will close it for you.  (See
  362. open().)  However, an explicit close on an input file resets the line
  363. counter ($.), while the implicit close done by open() does not.  Also,
  364. closing a pipe will wait for the process executing on the pipe to
  365. complete, in case you want to look at the output of the pipe
  366. afterwards.  Closing a pipe explicitly also puts the status value of
  367. the command into C<$?>.  Example:
  368.  
  369.     open(OUTPUT, '|sort >foo');    # pipe to sort
  370.     ...                # print stuff to output
  371.     close OUTPUT;        # wait for sort to finish
  372.     open(INPUT, 'foo');        # get sort's results
  373.  
  374. FILEHANDLE may be an expression whose value gives the real filehandle name.
  375.  
  376. =item closedir DIRHANDLE
  377.  
  378. Closes a directory opened by opendir().
  379.  
  380. =item connect SOCKET,NAME
  381.  
  382. Attempts to connect to a remote socket, just as the connect system call
  383. does.  Returns TRUE if it succeeded, FALSE otherwise.  NAME should be a
  384. packed address of the appropriate type for the socket.  See example in
  385. L<perlipc>.
  386.  
  387. =item cos EXPR
  388.  
  389. Returns the cosine of EXPR (expressed in radians).  If EXPR is omitted
  390. takes cosine of $_.
  391.  
  392. =item crypt PLAINTEXT,SALT
  393.  
  394. Encrypts a string exactly like the crypt(3) function in the C library.
  395. Useful for checking the password file for lousy passwords, amongst
  396. other things.  Only the guys wearing white hats should do this.  
  397.  
  398. Here's an example that makes sure that whoever runs this program knows
  399. their own password:
  400.  
  401.     $pwd = (getpwuid($<))[1];
  402.     $salt = substr($pwd, 0, 2);
  403.  
  404.     system "stty -echo";
  405.     print "Password: ";
  406.     chop($word = <STDIN>);
  407.     print "\n";
  408.     system "stty echo";
  409.  
  410.     if (crypt($word, $salt) ne $pwd) {
  411.     die "Sorry...\n";
  412.     } else {
  413.     print "ok\n";
  414.     } 
  415.  
  416. Of course, typing in your own password to whoever asks you 
  417. for it is unwise.
  418.  
  419. =item dbmclose ASSOC_ARRAY
  420.  
  421. [This function has been superseded by the untie() function.]
  422.  
  423. Breaks the binding between a DBM file and an associative array.
  424.  
  425. =item dbmopen ASSOC,DBNAME,MODE
  426.  
  427. [This function has been superseded by the tie() function.]
  428.  
  429. This binds a dbm(3) or ndbm(3) file to an associative array.  ASSOC is the
  430. name of the associative array.  (Unlike normal open, the first argument
  431. is I<NOT> a filehandle, even though it looks like one).  DBNAME is the
  432. name of the database (without the F<.dir> or F<.pag> extension).  If the
  433. database does not exist, it is created with protection specified by
  434. MODE (as modified by the umask()).  If your system only supports the
  435. older DBM functions, you may perform only one dbmopen() in your program.
  436. If your system has neither DBM nor ndbm, calling dbmopen() produces a
  437. fatal error.
  438.  
  439. If you don't have write access to the DBM file, you can only read
  440. associative array variables, not set them.  If you want to test whether
  441. you can write, either use file tests or try setting a dummy array entry
  442. inside an eval(), which will trap the error.
  443.  
  444. Note that functions such as keys() and values() may return huge array
  445. values when used on large DBM files.  You may prefer to use the each()
  446. function to iterate over large DBM files.  Example:
  447.  
  448.     # print out history file offsets
  449.     dbmopen(%HIST,'/usr/lib/news/history',0666);
  450.     while (($key,$val) = each %HIST) {
  451.     print $key, ' = ', unpack('L',$val), "\n";
  452.     }
  453.     dbmclose(%HIST);
  454.  
  455. =item defined EXPR
  456.  
  457. Returns a boolean value saying whether the lvalue EXPR has a real value
  458. or not.  Many operations return the undefined value under exceptional
  459. conditions, such as end of file, uninitialized variable, system error
  460. and such.  This function allows you to distinguish between an undefined
  461. null scalar and a defined null scalar with operations that might return
  462. a real null string, such as referencing elements of an array.  You may
  463. also check to see if arrays or subroutines exist.  Use of defined on
  464. predefined variables is not guaranteed to produce intuitive results.
  465.  
  466. When used on a hash array element, it tells you whether the value
  467. is defined, not whether the key exists in the hash.  Use exists() for that.
  468.  
  469. Examples:
  470.  
  471.     print if defined $switch{'D'};
  472.     print "$val\n" while defined($val = pop(@ary));
  473.     die "Can't readlink $sym: $!"
  474.     unless defined($value = readlink $sym);
  475.     eval '@foo = ()' if defined(@foo);
  476.     die "No XYZ package defined" unless defined %_XYZ;
  477.     sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
  478.  
  479. See also undef().
  480.  
  481. =item delete EXPR
  482.  
  483. Deletes the specified value from its hash array.  Returns the deleted
  484. value, or the undefined value if nothing was deleted.  Deleting from
  485. C<$ENV{}> modifies the environment.  Deleting from an array tied to a DBM
  486. file deletes the entry from the DBM file.  (But deleting from a tie()d
  487. hash doesn't necessarily return anything.)
  488.  
  489. The following deletes all the values of an associative array:
  490.  
  491.     foreach $key (keys %ARRAY) {
  492.     delete $ARRAY{$key};
  493.     }
  494.  
  495. (But it would be faster to use the undef() command.)  Note that the
  496. EXPR can be arbitrarily complicated as long as the final operation is
  497. a hash key lookup:
  498.  
  499.     delete $ref->[$x][$y]{$key};
  500.  
  501. =item die LIST
  502.  
  503. Outside of an eval(), prints the value of LIST to C<STDERR> and exits with
  504. the current value of $!  (errno).  If $! is 0, exits with the value of
  505. C<($? E<gt>E<gt> 8)> (backtick `command` status).  If C<($? E<gt>E<gt> 8)> is 0,
  506. exits with 255.  Inside an eval(), the error message is stuffed into C<$@>,
  507. and the eval() is terminated with the undefined value.
  508.  
  509. Equivalent examples:
  510.  
  511.     die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
  512.     chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" 
  513.  
  514. If the value of EXPR does not end in a newline, the current script line
  515. number and input line number (if any) are also printed, and a newline
  516. is supplied.  Hint: sometimes appending ", stopped" to your message
  517. will cause it to make better sense when the string "at foo line 123" is
  518. appended.  Suppose you are running script "canasta".
  519.  
  520.     die "/etc/games is no good";
  521.     die "/etc/games is no good, stopped";
  522.  
  523. produce, respectively
  524.  
  525.     /etc/games is no good at canasta line 123.
  526.     /etc/games is no good, stopped at canasta line 123.
  527.  
  528. See also exit() and warn().
  529.  
  530. =item do BLOCK
  531.  
  532. Not really a function.  Returns the value of the last command in the
  533. sequence of commands indicated by BLOCK.  When modified by a loop
  534. modifier, executes the BLOCK once before testing the loop condition.
  535. (On other statements the loop modifiers test the conditional first.)
  536.  
  537. =item do SUBROUTINE(LIST)
  538.  
  539. A deprecated form of subroutine call.  See L<perlsub>.
  540.  
  541. =item do EXPR
  542.  
  543. Uses the value of EXPR as a filename and executes the contents of the
  544. file as a Perl script.  Its primary use is to include subroutines
  545. from a Perl subroutine library.
  546.  
  547.     do 'stat.pl';
  548.  
  549. is just like
  550.  
  551.     eval `cat stat.pl`;
  552.  
  553. except that it's more efficient, more concise, keeps track of the
  554. current filename for error messages, and searches all the B<-I>
  555. libraries if the file isn't in the current directory (see also the @INC
  556. array in L<perlvar/Predefined Names>).  It's the same, however, in that it does
  557. reparse the file every time you call it, so you probably don't want to
  558. do this inside a loop.
  559.  
  560. Note that inclusion of library modules is better done with the
  561. use() and require() operators.
  562.  
  563. =item dump LABEL
  564.  
  565. This causes an immediate core dump.  Primarily this is so that you can
  566. use the B<undump> program to turn your core dump into an executable binary
  567. after having initialized all your variables at the beginning of the
  568. program.  When the new binary is executed it will begin by executing a
  569. C<goto LABEL> (with all the restrictions that C<goto> suffers).  Think of
  570. it as a goto with an intervening core dump and reincarnation.  If LABEL
  571. is omitted, restarts the program from the top.  WARNING: any files
  572. opened at the time of the dump will NOT be open any more when the
  573. program is reincarnated, with possible resulting confusion on the part
  574. of Perl.  See also B<-u> option in L<perlrun>.
  575.  
  576. Example:
  577.  
  578.     #!/usr/bin/perl
  579.     require 'getopt.pl';
  580.     require 'stat.pl';
  581.     %days = (
  582.     'Sun' => 1,
  583.     'Mon' => 2,
  584.     'Tue' => 3,
  585.     'Wed' => 4,
  586.     'Thu' => 5,
  587.     'Fri' => 6,
  588.     'Sat' => 7,
  589.     );
  590.  
  591.     dump QUICKSTART if $ARGV[0] eq '-d';
  592.  
  593.     QUICKSTART:
  594.     Getopt('f');
  595.  
  596. =item each ASSOC_ARRAY
  597.  
  598. Returns a 2 element array consisting of the key and value for the next
  599. value of an associative array, so that you can iterate over it.
  600. Entries are returned in an apparently random order.  When the array is
  601. entirely read, a null array is returned (which when assigned produces a
  602. FALSE (0) value).  The next call to each() after that will start
  603. iterating again.  The iterator can be reset only by reading all the
  604. elements from the array.  You should not add elements to an array while
  605. you're iterating over it.  There is a single iterator for each
  606. associative array, shared by all each(), keys() and values() function
  607. calls in the program.  The following prints out your environment like
  608. the printenv(1) program, only in a different order:
  609.  
  610.     while (($key,$value) = each %ENV) {
  611.     print "$key=$value\n";
  612.     }
  613.  
  614. See also keys() and values().
  615.  
  616. =item eof FILEHANDLE
  617.  
  618. =item eof
  619.  
  620. Returns 1 if the next read on FILEHANDLE will return end of file, or if
  621. FILEHANDLE is not open.  FILEHANDLE may be an expression whose value
  622. gives the real filehandle name.  (Note that this function actually
  623. reads a character and then ungetc()s it, so it is not very useful in an
  624. interactive context.)  Do not read from a terminal file (or call
  625. C<eof(FILEHANDLE)> on it) after end-of-file is reached.  Filetypes such
  626. as terminals may lose the end-of-file condition if you do.
  627.  
  628. An C<eof> without an argument uses the last file read as argument.
  629. Empty parentheses () may be used to indicate
  630. the pseudo file formed of the files listed on the command line, i.e.
  631. C<eof()> is reasonable to use inside a while (<>) loop to detect the end
  632. of only the last file.  Use C<eof(ARGV)> or eof without the parentheses to
  633. test I<EACH> file in a while (<>) loop.  Examples:
  634.  
  635.     # reset line numbering on each input file
  636.     while (<>) {
  637.     print "$.\t$_";
  638.     close(ARGV) if (eof);    # Not eof().
  639.     }
  640.  
  641.     # insert dashes just before last line of last file
  642.     while (<>) {
  643.     if (eof()) {
  644.         print "--------------\n";
  645.         close(ARGV);    # close or break; is needed if we
  646.                 # are reading from the terminal
  647.     }
  648.     print;
  649.     }
  650.  
  651. Practical hint: you almost never need to use C<eof> in Perl, because the
  652. input operators return undef when they run out of data.
  653.  
  654. =item eval EXPR
  655.  
  656. =item eval BLOCK
  657.  
  658. EXPR is parsed and executed as if it were a little Perl program.  It
  659. is executed in the context of the current Perl program, so that any
  660. variable settings, subroutine or format definitions remain afterwards.
  661. The value returned is the value of the last expression evaluated, or a
  662. return statement may be used, just as with subroutines.
  663.  
  664. If there is a syntax error or runtime error, or a die() statement is
  665. executed, an undefined value is returned by eval(), and C<$@> is set to the
  666. error message.  If there was no error, C<$@> is guaranteed to be a null
  667. string.  If EXPR is omitted, evaluates $_.  The final semicolon, if
  668. any, may be omitted from the expression.
  669.  
  670. Note that, since eval() traps otherwise-fatal errors, it is useful for
  671. determining whether a particular feature (such as dbmopen() or symlink())
  672. is implemented.  It is also Perl's exception trapping mechanism, where
  673. the die operator is used to raise exceptions.
  674.  
  675. If the code to be executed doesn't vary, you may use the eval-BLOCK
  676. form to trap run-time errors without incurring the penalty of
  677. recompiling each time.  The error, if any, is still returned in C<$@>.
  678. Examples:
  679.  
  680.     # make divide-by-zero non-fatal
  681.     eval { $answer = $a / $b; }; warn $@ if $@;
  682.  
  683.     # same thing, but less efficient
  684.     eval '$answer = $a / $b'; warn $@ if $@;
  685.  
  686.     # a compile-time error
  687.     eval { $answer = };
  688.  
  689.     # a run-time error
  690.     eval '$answer =';    # sets $@
  691.  
  692. With an eval(), you should be especially careful to remember what's 
  693. being looked at when:
  694.  
  695.     eval $x;        # CASE 1
  696.     eval "$x";        # CASE 2
  697.  
  698.     eval '$x';        # CASE 3
  699.     eval { $x };    # CASE 4
  700.  
  701.     eval "\$$x++"    # CASE 5
  702.     $$x++;        # CASE 6
  703.  
  704. Cases 1 and 2 above behave identically: they run the code contained in the
  705. variable $x.  (Although case 2 has misleading double quotes making the
  706. reader wonder what else might be happening (nothing is).) Cases 3 and 4
  707. likewise behave in the same way: they run the code <$x>, which does
  708. nothing at all.  (Case 4 is preferred for purely visual reasons.) Case 5
  709. is a place where normally you I<WOULD> like to use double quotes, except
  710. in that particular situation, you can just use symbolic references
  711. instead, as in case 6.
  712.  
  713. =item exec LIST
  714.  
  715. The exec() function executes a system command I<AND NEVER RETURNS>.  Use
  716. the system() function if you want it to return.
  717.  
  718. If there is more than one argument in LIST, or if LIST is an array with
  719. more than one value, calls execvp(3) with the arguments in LIST.  If
  720. there is only one scalar argument, the argument is checked for shell
  721. metacharacters.  If there are any, the entire argument is passed to
  722. C</bin/sh -c> for parsing.  If there are none, the argument is split
  723. into words and passed directly to execvp(), which is more efficient.
  724. Note: exec() (and system(0) do not flush your output buffer, so you may
  725. need to set C<$|> to avoid lost output.  Examples:
  726.  
  727.     exec '/bin/echo', 'Your arguments are: ', @ARGV;
  728.     exec "sort $outfile | uniq";
  729.  
  730. If you don't really want to execute the first argument, but want to lie
  731. to the program you are executing about its own name, you can specify
  732. the program you actually want to run as an "indirect object" (without a
  733. comma) in front of the LIST.  (This always forces interpretation of the
  734. LIST as a multi-valued list, even if there is only a single scalar in
  735. the list.)  Example:
  736.  
  737.     $shell = '/bin/csh';
  738.     exec $shell '-sh';        # pretend it's a login shell
  739.  
  740. or, more directly,
  741.  
  742.     exec {'/bin/csh'} '-sh';    # pretend it's a login shell
  743.  
  744. =item exists EXPR
  745.  
  746. Returns TRUE if the specified hash key exists in its hash array, even
  747. if the corresponding value is undefined.
  748.  
  749.     print "Exists\n" if exists $array{$key};
  750.     print "Defined\n" if defined $array{$key};
  751.     print "True\n" if $array{$key};
  752.  
  753. A hash element can only be TRUE if it's defined, and defined if
  754. it exists, but the reverse doesn't necessarily hold true.
  755.  
  756. Note that the EXPR can be arbitrarily complicated as long as the final
  757. operation is a hash key lookup:
  758.  
  759.     if (exists $ref->[$x][$y]{$key}) { ... }
  760.  
  761. =item exit EXPR
  762.  
  763. Evaluates EXPR and exits immediately with that value.  (Actually, it
  764. calls any defined C<END> routines first, but the C<END> routines may not
  765. abort the exit.  Likewise any object destructors that need to be called
  766. are called before exit.)  Example:
  767.  
  768.     $ans = <STDIN>;
  769.     exit 0 if $ans =~ /^[Xx]/;
  770.  
  771. See also die().  If EXPR is omitted, exits with 0 status.
  772.  
  773. =item exp EXPR
  774.  
  775. Returns I<e> (the natural logarithm base) to the power of EXPR.  
  776. If EXPR is omitted, gives C<exp($_)>.
  777.  
  778. =item fcntl FILEHANDLE,FUNCTION,SCALAR
  779.  
  780. Implements the fcntl(2) function.  You'll probably have to say
  781.  
  782.     use Fcntl;
  783.  
  784. first to get the correct function definitions.  Argument processing and
  785. value return works just like ioctl() below.  Note that fcntl() will produce
  786. a fatal error if used on a machine that doesn't implement fcntl(2).
  787. For example:
  788.  
  789.     use Fcntl;
  790.     fcntl($filehandle, F_GETLK, $packed_return_buffer);
  791.  
  792. =item fileno FILEHANDLE
  793.  
  794. Returns the file descriptor for a filehandle.  This is useful for
  795. constructing bitmaps for select().  If FILEHANDLE is an expression, the
  796. value is taken as the name of the filehandle.
  797.  
  798. =item flock FILEHANDLE,OPERATION
  799.  
  800. Calls flock(2) on FILEHANDLE.  See L<flock(2)> for
  801. definition of OPERATION.  Returns TRUE for success, FALSE on failure.
  802. Will produce a fatal error if used on a machine that doesn't implement
  803. flock(2).  Here's a mailbox appender for BSD systems.
  804.  
  805.     $LOCK_SH = 1;
  806.     $LOCK_EX = 2;
  807.     $LOCK_NB = 4;
  808.     $LOCK_UN = 8;
  809.  
  810.     sub lock {
  811.     flock(MBOX,$LOCK_EX);
  812.     # and, in case someone appended
  813.     # while we were waiting...
  814.     seek(MBOX, 0, 2);
  815.     }
  816.  
  817.     sub unlock {
  818.     flock(MBOX,$LOCK_UN);
  819.     }
  820.  
  821.     open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
  822.         or die "Can't open mailbox: $!";
  823.  
  824.     lock();
  825.     print MBOX $msg,"\n\n";
  826.     unlock();
  827.  
  828. Note that flock() can't lock things over the network.  You need to do
  829. locking with fcntl() for that.
  830.  
  831. =item fork
  832.  
  833. Does a fork(2) system call.  Returns the child pid to the parent process
  834. and 0 to the child process, or undef if the fork is unsuccessful.
  835. Note: unflushed buffers remain unflushed in both processes, which means
  836. you may need to set C<$|> ($AUTOFLUSH in English) or call the 
  837. autoflush() FileHandle method to avoid duplicate output.
  838.  
  839. If you fork() without ever waiting on your children, you will accumulate
  840. zombies:
  841.  
  842.     $SIG{'CHLD'} = sub { wait };
  843.  
  844. There's also the double-fork trick (error checking on 
  845. fork() returns omitted);
  846.  
  847.     unless ($pid = fork) {
  848.     unless (fork) {
  849.         exec "what you really wanna do";
  850.         die "no exec";
  851.         # ... or ...
  852.         some_perl_code_here;
  853.         exit 0;
  854.     }
  855.     exit 0;
  856.     }
  857.     waitpid($pid,0);
  858.  
  859.  
  860. =item formline PICTURE, LIST
  861.  
  862. This is an internal function used by formats, though you may call it
  863. too.  It formats (see L<perlform>) a list of values according to the
  864. contents of PICTURE, placing the output into the format output
  865. accumulator, C<$^A>.  Eventually, when a write() is done, the contents of
  866. C<$^A> are written to some filehandle, but you could also read C<$^A>
  867. yourself and then set C<$^A> back to "".  Note that a format typically
  868. does one formline() per line of form, but the formline() function itself
  869. doesn't care how many newlines are embedded in the PICTURE.  This means
  870. that the ~ and ~~ tokens will treat the entire PICTURE as a single line.
  871. You may therefore need to use multiple formlines to implement a single
  872. record format, just like the format compiler.
  873.  
  874. Be careful if you put double quotes around the picture, since an "C<@>"
  875. character may be taken to mean the beginning of an array name.
  876. formline() always returns TRUE.
  877.  
  878. =item getc FILEHANDLE
  879.  
  880. =item getc
  881.  
  882. Returns the next character from the input file attached to FILEHANDLE,
  883. or a null string at end of file.  If FILEHANDLE is omitted, reads from STDIN.
  884.  
  885. =item getlogin
  886.  
  887. Returns the current login from F</etc/utmp>, if any.  If null, use
  888. getpwuid().
  889.  
  890.     $login = getlogin || (getpwuid($<))[0] || "Kilroy";
  891.  
  892. =item getpeername SOCKET
  893.  
  894. Returns the packed sockaddr address of other end of the SOCKET connection.
  895.  
  896.     # An internet sockaddr
  897.     $sockaddr = 'S n a4 x8';
  898.     $hersockaddr = getpeername(S);
  899.     ($family, $port, $heraddr) = unpack($sockaddr,$hersockaddr);
  900.  
  901. =item getpgrp PID
  902.  
  903. Returns the current process group for the specified PID, 0 for the
  904. current process.  Will produce a fatal error if used on a machine that
  905. doesn't implement getpgrp(2).  If PID is omitted, returns process
  906. group of current process.
  907.  
  908. =item getppid
  909.  
  910. Returns the process id of the parent process.
  911.  
  912. =item getpriority WHICH,WHO
  913.  
  914. Returns the current priority for a process, a process group, or a
  915. user.  (See L<getpriority(2)>.)  Will produce a fatal error if used on a
  916. machine that doesn't implement getpriority(2).
  917.  
  918. =item getpwnam NAME
  919.  
  920. =item getgrnam NAME
  921.  
  922. =item gethostbyname NAME
  923.  
  924. =item getnetbyname NAME
  925.  
  926. =item getprotobyname NAME
  927.  
  928. =item getpwuid UID
  929.  
  930. =item getgrgid GID
  931.  
  932. =item getservbyname NAME,PROTO
  933.  
  934. =item gethostbyaddr ADDR,ADDRTYPE
  935.  
  936. =item getnetbyaddr ADDR,ADDRTYPE
  937.  
  938. =item getprotobynumber NUMBER
  939.  
  940. =item getservbyport PORT,PROTO
  941.  
  942. =item getpwent
  943.  
  944. =item getgrent
  945.  
  946. =item gethostent
  947.  
  948. =item getnetent
  949.  
  950. =item getprotoent
  951.  
  952. =item getservent
  953.  
  954. =item setpwent
  955.  
  956. =item setgrent
  957.  
  958. =item sethostent STAYOPEN
  959.  
  960. =item setnetent STAYOPEN
  961.  
  962. =item setprotoent STAYOPEN
  963.  
  964. =item setservent STAYOPEN
  965.  
  966. =item endpwent
  967.  
  968. =item endgrent
  969.  
  970. =item endhostent
  971.  
  972. =item endnetent
  973.  
  974. =item endprotoent
  975.  
  976. =item endservent
  977.  
  978. These routines perform the same functions as their counterparts in the
  979. system library.  Within a list context, the return values from the
  980. various get routines are as follows:
  981.  
  982.     ($name,$passwd,$uid,$gid,
  983.        $quota,$comment,$gcos,$dir,$shell) = getpw*
  984.     ($name,$passwd,$gid,$members) = getgr*
  985.     ($name,$aliases,$addrtype,$length,@addrs) = gethost*
  986.     ($name,$aliases,$addrtype,$net) = getnet*
  987.     ($name,$aliases,$proto) = getproto*
  988.     ($name,$aliases,$port,$proto) = getserv*
  989.  
  990. (If the entry doesn't exist you get a null list.)
  991.  
  992. Within a scalar context, you get the name, unless the function was a
  993. lookup by name, in which case you get the other thing, whatever it is.
  994. (If the entry doesn't exist you get the undefined value.)  For example:
  995.  
  996.     $uid = getpwnam
  997.     $name = getpwuid
  998.     $name = getpwent
  999.     $gid = getgrnam
  1000.     $name = getgrgid
  1001.     $name = getgrent
  1002.     etc.
  1003.  
  1004. The $members value returned by I<getgr*()> is a space separated list of
  1005. the login names of the members of the group.
  1006.  
  1007. For the I<gethost*()> functions, if the C<h_errno> variable is supported in
  1008. C, it will be returned to you via C<$?> if the function call fails.  The
  1009. @addrs value returned by a successful call is a list of the raw
  1010. addresses returned by the corresponding system library call.  In the
  1011. Internet domain, each address is four bytes long and you can unpack it
  1012. by saying something like:
  1013.  
  1014.     ($a,$b,$c,$d) = unpack('C4',$addr[0]);
  1015.  
  1016. =item getsockname SOCKET
  1017.  
  1018. Returns the packed sockaddr address of this end of the SOCKET connection.
  1019.  
  1020.     # An internet sockaddr
  1021.     $sockaddr = 'S n a4 x8';
  1022.     $mysockaddr = getsockname(S);
  1023.     ($family, $port, $myaddr) =
  1024.             unpack($sockaddr,$mysockaddr);
  1025.  
  1026. =item getsockopt SOCKET,LEVEL,OPTNAME
  1027.  
  1028. Returns the socket option requested, or undefined if there is an error.
  1029.  
  1030. =item glob EXPR
  1031.  
  1032. Returns the value of EXPR with filename expansions such as a shell
  1033. would do.  This is the internal function implementing the <*.*>
  1034. operator.
  1035.  
  1036. =item gmtime EXPR
  1037.  
  1038. Converts a time as returned by the time function to a 9-element array
  1039. with the time localized for the Greenwich timezone.  Typically used as
  1040. follows:
  1041.  
  1042.  
  1043.     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  1044.                         gmtime(time);
  1045.  
  1046. All array elements are numeric, and come straight out of a struct tm.
  1047. In particular this means that $mon has the range 0..11 and $wday has
  1048. the range 0..6.  If EXPR is omitted, does C<gmtime(time())>.
  1049.  
  1050. =item goto LABEL
  1051.  
  1052. =item goto EXPR
  1053.  
  1054. =item goto &NAME
  1055.  
  1056. The goto-LABEL form finds the statement labeled with LABEL and resumes
  1057. execution there.  It may not be used to go into any construct that
  1058. requires initialization, such as a subroutine or a foreach loop.  It
  1059. also can't be used to go into a construct that is optimized away.  It
  1060. can be used to go almost anywhere else within the dynamic scope,
  1061. including out of subroutines, but it's usually better to use some other
  1062. construct such as last or die.  The author of Perl has never felt the
  1063. need to use this form of goto (in Perl, that is--C is another matter).
  1064.  
  1065. The goto-EXPR form expects a label name, whose scope will be resolved
  1066. dynamically.  This allows for computed gotos per FORTRAN, but isn't
  1067. necessarily recommended if you're optimizing for maintainability:
  1068.  
  1069.     goto ("FOO", "BAR", "GLARCH")[$i];
  1070.  
  1071. The goto-&NAME form is highly magical, and substitutes a call to the
  1072. named subroutine for the currently running subroutine.  This is used by
  1073. AUTOLOAD subroutines that wish to load another subroutine and then
  1074. pretend that the other subroutine had been called in the first place
  1075. (except that any modifications to @_ in the current subroutine are
  1076. propagated to the other subroutine.)  After the goto, not even caller()
  1077. will be able to tell that this routine was called first.
  1078.  
  1079. =item grep BLOCK LIST
  1080.  
  1081. =item grep EXPR,LIST
  1082.  
  1083. Evaluates the BLOCK or EXPR for each element of LIST (locally setting
  1084. $_ to each element) and returns the list value consisting of those
  1085. elements for which the expression evaluated to TRUE.  In a scalar
  1086. context, returns the number of times the expression was TRUE.
  1087.  
  1088.     @foo = grep(!/^#/, @bar);    # weed out comments
  1089.  
  1090. or equivalently,
  1091.  
  1092.     @foo = grep {!/^#/} @bar;    # weed out comments
  1093.  
  1094. Note that, since $_ is a reference into the list value, it can be used
  1095. to modify the elements of the array.  While this is useful and
  1096. supported, it can cause bizarre results if the LIST is not a named
  1097. array.
  1098.  
  1099. =item hex EXPR
  1100.  
  1101. Returns the decimal value of EXPR interpreted as an hex string.  (To
  1102. interpret strings that might start with 0 or 0x see oct().)  If EXPR is
  1103. omitted, uses $_.
  1104.  
  1105. =item import
  1106.  
  1107. There is no built-in import() function.  It is merely an ordinary
  1108. method subroutine defined (or inherited) by modules that wish to export
  1109. names to another module.  The use() function calls the import() method
  1110. for the package used.  See also L</use> and L<perlmod>.
  1111.  
  1112. =item index STR,SUBSTR,POSITION
  1113.  
  1114. =item index STR,SUBSTR
  1115.  
  1116. Returns the position of the first occurrence of SUBSTR in STR at or
  1117. after POSITION.  If POSITION is omitted, starts searching from the
  1118. beginning of the string.  The return value is based at 0, or whatever
  1119. you've set the $[ variable to.  If the substring is not found, returns
  1120. one less than the base, ordinarily -1.
  1121.  
  1122. =item int EXPR
  1123.  
  1124. Returns the integer portion of EXPR.  If EXPR is omitted, uses $_.
  1125.  
  1126. =item ioctl FILEHANDLE,FUNCTION,SCALAR
  1127.  
  1128. Implements the ioctl(2) function.  You'll probably have to say
  1129.  
  1130.     require "ioctl.ph";    # probably /usr/local/lib/perl/ioctl.ph
  1131.  
  1132. first to get the correct function definitions.  If ioctl.ph doesn't
  1133. exist or doesn't have the correct definitions you'll have to roll your
  1134. own, based on your C header files such as <sys/ioctl.h>.  (There is a
  1135. Perl script called B<h2ph> that comes with the Perl kit which may help you
  1136. in this.)  SCALAR will be read and/or written depending on the
  1137. FUNCTION--a pointer to the string value of SCALAR will be passed as the
  1138. third argument of the actual ioctl call.  (If SCALAR has no string
  1139. value but does have a numeric value, that value will be passed rather
  1140. than a pointer to the string value.  To guarantee this to be TRUE, add
  1141. a 0 to the scalar before using it.)  The pack() and unpack() functions
  1142. are useful for manipulating the values of structures used by ioctl().
  1143. The following example sets the erase character to DEL.
  1144.  
  1145.     require 'ioctl.ph';
  1146.     $sgttyb_t = "ccccs";        # 4 chars and a short
  1147.     if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
  1148.     @ary = unpack($sgttyb_t,$sgttyb);
  1149.     $ary[2] = 127;
  1150.     $sgttyb = pack($sgttyb_t,@ary);
  1151.     ioctl(STDIN,$TIOCSETP,$sgttyb)
  1152.         || die "Can't ioctl: $!";
  1153.     }
  1154.  
  1155. The return value of ioctl (and fcntl) is as follows:
  1156.  
  1157.     if OS returns:        then Perl returns:
  1158.         -1                undefined value
  1159.          0             string "0 but true"
  1160.     anything else            that number
  1161.  
  1162. Thus Perl returns TRUE on success and FALSE on failure, yet you can
  1163. still easily determine the actual value returned by the operating
  1164. system:
  1165.  
  1166.     ($retval = ioctl(...)) || ($retval = -1);
  1167.     printf "System returned %d\n", $retval;
  1168.  
  1169. =item join EXPR,LIST
  1170.  
  1171. Joins the separate strings of LIST or ARRAY into a single string with
  1172. fields separated by the value of EXPR, and returns the string.
  1173. Example:
  1174.  
  1175.     $_ = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  1176.  
  1177. See L<perlfunc/split>.
  1178.  
  1179. =item keys ASSOC_ARRAY
  1180.  
  1181. Returns a normal array consisting of all the keys of the named
  1182. associative array.  (In a scalar context, returns the number of keys.)
  1183. The keys are returned in an apparently random order, but it is the same
  1184. order as either the values() or each() function produces (given that
  1185. the associative array has not been modified).  Here is yet another way
  1186. to print your environment:
  1187.  
  1188.     @keys = keys %ENV;
  1189.     @values = values %ENV;
  1190.     while ($#keys >= 0) {
  1191.     print pop(@keys), '=', pop(@values), "\n";
  1192.     }
  1193.  
  1194. or how about sorted by key:
  1195.  
  1196.     foreach $key (sort(keys %ENV)) {
  1197.     print $key, '=', $ENV{$key}, "\n";
  1198.     }
  1199.  
  1200. =item kill LIST
  1201.  
  1202. Sends a signal to a list of processes.  The first element of the list
  1203. must be the signal to send.  Returns the number of processes
  1204. successfully signaled.
  1205.  
  1206.     $cnt = kill 1, $child1, $child2;
  1207.     kill 9, @goners;
  1208.  
  1209. Unlike in the shell, in Perl
  1210. if the I<SIGNAL> is negative, it kills process groups instead of processes.
  1211. (On System V, a negative I<PROCESS> number will also kill process
  1212. groups, but that's not portable.)  That means you usually want to use
  1213. positive not negative signals.  You may also use a signal name in quotes.
  1214.  
  1215. =item last LABEL
  1216.  
  1217. =item last
  1218.  
  1219. The C<last> command is like the C<break> statement in C (as used in
  1220. loops); it immediately exits the loop in question.  If the LABEL is
  1221. omitted, the command refers to the innermost enclosing loop.  The
  1222. C<continue> block, if any, is not executed:
  1223.  
  1224.     line: while (<STDIN>) {
  1225.     last line if /^$/;    # exit when done with header
  1226.     ...
  1227.     }
  1228.  
  1229. =item lc EXPR
  1230.  
  1231. Returns an lowercased version of EXPR.  This is the internal function
  1232. implementing the \L escape in double-quoted strings.
  1233.  
  1234. =item lcfirst EXPR
  1235.  
  1236. Returns the value of EXPR with the first character lowercased.  This is
  1237. the internal function implementing the \l escape in double-quoted strings.
  1238.  
  1239. =item length EXPR
  1240.  
  1241. Returns the length in characters of the value of EXPR.  If EXPR is
  1242. omitted, returns length of $_.
  1243.  
  1244. =item link OLDFILE,NEWFILE
  1245.  
  1246. Creates a new filename linked to the old filename.  Returns 1 for
  1247. success, 0 otherwise.
  1248.  
  1249. =item listen SOCKET,QUEUESIZE
  1250.  
  1251. Does the same thing that the listen system call does.  Returns TRUE if
  1252. it succeeded, FALSE otherwise.  See example in L<perlipc>.
  1253.  
  1254. =item local EXPR
  1255.  
  1256. In general, you should be using "my" instead of "local", because it's
  1257. faster and safer.  Format variables often use "local" though, as
  1258. do other variables whose current value must be visible to called
  1259. subroutines.  This is known as dynamic scoping.  Lexical scoping is
  1260. done with "my", which works more like C's auto declarations.
  1261.  
  1262. A local modifies the listed variables to be local to the enclosing block,
  1263. subroutine, eval or "do".  If more than one value is listed, the list
  1264. must be placed in parens.  All the listed elements must be legal
  1265. lvalues.  This operator works by saving the current values of those
  1266. variables in LIST on a hidden stack and restoring them upon exiting the
  1267. block, subroutine or eval.  This means that called subroutines can also
  1268. reference the local variable, but not the global one.  The LIST may be
  1269. assigned to if desired, which allows you to initialize your local
  1270. variables.  (If no initializer is given for a particular variable, it
  1271. is created with an undefined value.)  Commonly this is used to name the
  1272. parameters to a subroutine.  Examples:
  1273.  
  1274.     sub RANGEVAL {
  1275.     local($min, $max, $thunk) = @_;
  1276.     local $result = '';
  1277.     local $i;
  1278.  
  1279.     # Presumably $thunk makes reference to $i
  1280.  
  1281.     for ($i = $min; $i < $max; $i++) {
  1282.         $result .= eval $thunk;
  1283.     }
  1284.  
  1285.     $result;
  1286.     }
  1287.  
  1288.  
  1289.     if ($sw eq '-v') {
  1290.     # init local array with global array
  1291.     local @ARGV = @ARGV;
  1292.     unshift(@ARGV,'echo');
  1293.     system @ARGV;
  1294.     }
  1295.     # @ARGV restored
  1296.  
  1297.  
  1298.     # temporarily add to digits associative array
  1299.     if ($base12) {
  1300.     # (NOTE: not claiming this is efficient!)
  1301.     local(%digits) = (%digits,'t',10,'e',11);
  1302.     parse_num();
  1303.     }
  1304.  
  1305. Note that local() is a run-time command, and so gets executed every
  1306. time through a loop.  In Perl 4 it used more stack storage each
  1307. time until the loop was exited.  Perl 5 reclaims the space each time
  1308. through, but it's still more efficient to declare your variables
  1309. outside the loop.
  1310.  
  1311. A local is simply a modifier on an lvalue expression.
  1312. When you assign to a localized EXPR, the local doesn't change whether
  1313. EXPR is viewed as a scalar or an array.  So
  1314.  
  1315.     local($foo) = <STDIN>;
  1316.     local @FOO = <STDIN>;
  1317.  
  1318. both supply a list context to the righthand side, while
  1319.  
  1320.     local $foo = <STDIN>;
  1321.  
  1322. supplies a scalar context.
  1323.  
  1324. =item localtime EXPR
  1325.  
  1326. Converts a time as returned by the time function to a 9-element array
  1327. with the time analyzed for the local timezone.  Typically used as
  1328. follows:
  1329.  
  1330.     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  1331.                         localtime(time);
  1332.  
  1333. All array elements are numeric, and come straight out of a struct tm.
  1334. In particular this means that $mon has the range 0..11 and $wday has
  1335. the range 0..6.  If EXPR is omitted, does localtime(time).
  1336.  
  1337. In a scalar context, prints out the ctime(3) value:
  1338.  
  1339.     $now_string = localtime;  # e.g. "Thu Oct 13 04:54:34 1994"
  1340.  
  1341. See also L<perlmod/timelocal> and the strftime(3) function available
  1342. via the POSIX modulie.
  1343.  
  1344. =item log EXPR
  1345.  
  1346. Returns logarithm (base I<e>) of EXPR.  If EXPR is omitted, returns log
  1347. of $_.
  1348.  
  1349. =item lstat FILEHANDLE
  1350.  
  1351. =item lstat EXPR
  1352.  
  1353. Does the same thing as the stat() function, but stats a symbolic link
  1354. instead of the file the symbolic link points to.  If symbolic links are
  1355. unimplemented on your system, a normal stat() is done.
  1356.  
  1357. =item m//
  1358.  
  1359. The match operator.  See L<perlop>.
  1360.  
  1361. =item map BLOCK LIST
  1362.  
  1363. =item map EXPR,LIST
  1364.  
  1365. Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each
  1366. element) and returns the list value composed of the results of each such
  1367. evaluation.  Evaluates BLOCK or EXPR in a list context, so each element of LIST
  1368. may produce zero, one, or more elements in the returned value.
  1369.  
  1370.     @chars = map(chr, @nums);
  1371.  
  1372. translates a list of numbers to the corresponding characters.  And
  1373.  
  1374.     %hash = map {&key($_), $_} @array;
  1375.  
  1376. is just a funny way to write
  1377.  
  1378.     %hash = ();
  1379.     foreach $_ (@array) {
  1380.     $hash{&key($_)} = $_;
  1381.     }
  1382.  
  1383. =item mkdir FILENAME,MODE
  1384.  
  1385. Creates the directory specified by FILENAME, with permissions specified
  1386. by MODE (as modified by umask).  If it succeeds it returns 1, otherwise
  1387. it returns 0 and sets $! (errno).
  1388.  
  1389. =item msgctl ID,CMD,ARG
  1390.  
  1391. Calls the System V IPC function msgctl.  If CMD is &IPC_STAT, then ARG
  1392. must be a variable which will hold the returned msqid_ds structure.
  1393. Returns like ioctl: the undefined value for error, "0 but true" for
  1394. zero, or the actual return value otherwise.
  1395.  
  1396. =item msgget KEY,FLAGS
  1397.  
  1398. Calls the System V IPC function msgget.  Returns the message queue id,
  1399. or the undefined value if there is an error.
  1400.  
  1401. =item msgsnd ID,MSG,FLAGS
  1402.  
  1403. Calls the System V IPC function msgsnd to send the message MSG to the
  1404. message queue ID.  MSG must begin with the long integer message type,
  1405. which may be created with C<pack("L", $type)>.  Returns TRUE if
  1406. successful, or FALSE if there is an error.
  1407.  
  1408. =item msgrcv ID,VAR,SIZE,TYPE,FLAGS
  1409.  
  1410. Calls the System V IPC function msgrcv to receive a message from
  1411. message queue ID into variable VAR with a maximum message size of
  1412. SIZE.  Note that if a message is received, the message type will be the
  1413. first thing in VAR, and the maximum length of VAR is SIZE plus the size
  1414. of the message type.  Returns TRUE if successful, or FALSE if there is
  1415. an error.
  1416.  
  1417. =item my EXPR
  1418.  
  1419. A "my" declares the listed variables to be local (lexically) to the
  1420. enclosing block, subroutine, eval or "do".  If more than one value is
  1421. listed, the list must be placed in parens.  All the listed elements
  1422. must be legal lvalues.  Only alphanumeric identifiers may be lexically
  1423. scoped--magical builtins like $/ must be localized with "local"
  1424. instead.  In particular, you're not allowed to say
  1425.  
  1426.     my $_;    # Illegal.
  1427.  
  1428. Unlike the "local" declaration, variables declared with "my"
  1429. are totally hidden from the outside world, including any called
  1430. subroutines (even if it's the same subroutine--every call gets its own
  1431. copy).
  1432.  
  1433. (An eval(), however, can see the lexical variables of the scope it is
  1434. being evaluated in so long as the names aren't hidden by declarations within
  1435. the eval() itself.  See L<perlref>.)
  1436.  
  1437. The EXPR may be assigned to if desired, which allows you to initialize
  1438. your variables.  (If no initializer is given for a particular
  1439. variable, it is created with an undefined value.)  Commonly this is
  1440. used to name the parameters to a subroutine.  Examples:
  1441.  
  1442.     sub RANGEVAL {
  1443.     my($min, $max, $thunk) = @_;
  1444.     my $result = '';
  1445.     my $i;
  1446.  
  1447.     # Presumably $thunk makes reference to $i
  1448.  
  1449.     for ($i = $min; $i < $max; $i++) {
  1450.         $result .= eval $thunk;
  1451.     }
  1452.  
  1453.     $result;
  1454.     }
  1455.  
  1456.  
  1457.     if ($sw eq '-v') {
  1458.     # init my array with global array
  1459.     my @ARGV = @ARGV;
  1460.     unshift(@ARGV,'echo');
  1461.     system @ARGV;
  1462.     }
  1463.     # Outer @ARGV again visible
  1464.  
  1465. The "my" is simply a modifier on something you might assign to.
  1466. So when you do assign to the EXPR, the "my" doesn't change whether
  1467. EXPR is viewed as a scalar or an array.  So
  1468.  
  1469.     my ($foo) = <STDIN>;
  1470.     my @FOO = <STDIN>;
  1471.  
  1472. both supply a list context to the righthand side, while
  1473.  
  1474.     my $foo = <STDIN>;
  1475.  
  1476. supplies a scalar context.  But the following only declares one variable:
  1477.  
  1478.     my $foo, $bar = 1;
  1479.  
  1480. That has the same effect as
  1481.  
  1482.     my $foo;
  1483.     $bar = 1;
  1484.  
  1485. The declared variable is not introduced (is not visible) until after
  1486. the current statement.  Thus,
  1487.  
  1488.     my $x = $x;
  1489.  
  1490. can be used to initialize the new $x with the value of the old $x, and 
  1491. the expression
  1492.  
  1493.     my $x = 123 and $x == 123
  1494.  
  1495. is false unless the old $x happened to have the value 123.
  1496.  
  1497. Some users may wish to encourage the use of lexically scoped variables.
  1498. As an aid to catching implicit references to package variables,
  1499. if you say
  1500.  
  1501.     use strict 'vars';
  1502.  
  1503. then any variable reference from there to the end of the enclosing
  1504. block must either refer to a lexical variable, or must be fully
  1505. qualified with the package name.  A compilation error results
  1506. otherwise.  An inner block may countermand this with S<"no strict 'vars'">.
  1507.  
  1508. =item next LABEL
  1509.  
  1510. =item next
  1511.  
  1512. The C<next> command is like the C<continue> statement in C; it starts
  1513. the next iteration of the loop:
  1514.  
  1515.     line: while (<STDIN>) {
  1516.     next line if /^#/;    # discard comments
  1517.     ...
  1518.     }
  1519.  
  1520. Note that if there were a C<continue> block on the above, it would get
  1521. executed even on discarded lines.  If the LABEL is omitted, the command
  1522. refers to the innermost enclosing loop.
  1523.  
  1524. =item no Module LIST
  1525.  
  1526. See the "use" function, which "no" is the opposite of.
  1527.  
  1528. =item oct EXPR
  1529.  
  1530. Returns the decimal value of EXPR interpreted as an octal string.  (If
  1531. EXPR happens to start off with 0x, interprets it as a hex string
  1532. instead.)  The following will handle decimal, octal, and hex in the
  1533. standard Perl or C notation:
  1534.  
  1535.     $val = oct($val) if $val =~ /^0/;
  1536.  
  1537. If EXPR is omitted, uses $_.
  1538.  
  1539. =item open FILEHANDLE,EXPR
  1540.  
  1541. =item open FILEHANDLE
  1542.  
  1543. Opens the file whose filename is given by EXPR, and associates it with
  1544. FILEHANDLE.  If FILEHANDLE is an expression, its value is used as the
  1545. name of the real filehandle wanted.  If EXPR is omitted, the scalar
  1546. variable of the same name as the FILEHANDLE contains the filename.  If
  1547. the filename begins with "<" or nothing, the file is opened for input.
  1548. If the filename begins with ">", the file is opened for output.  If the
  1549. filename begins with ">>", the file is opened for appending.  (You can
  1550. put a '+' in front of the '>' or '<' to indicate that you want both
  1551. read and write access to the file.)  If the filename begins with "|",
  1552. the filename is interpreted as a command to which output is to be
  1553. piped, and if the filename ends with a "|", the filename is interpreted
  1554. as command which pipes input to us.  (You may not have a command that
  1555. pipes both in and out.)  Opening '-' opens STDIN and opening '>-'
  1556. opens STDOUT.  Open returns non-zero upon success, the undefined
  1557. value otherwise.  If the open involved a pipe, the return value happens
  1558. to be the pid of the subprocess.  Examples:
  1559.  
  1560.     $ARTICLE = 100;
  1561.     open ARTICLE or die "Can't find article $ARTICLE: $!\n";
  1562.     while (<ARTICLE>) {...
  1563.  
  1564.     open(LOG, '>>/usr/spool/news/twitlog'); # (log is reserved)
  1565.  
  1566.     open(article, "caesar <$article |");    # decrypt article
  1567.  
  1568.     open(extract, "|sort >/tmp/Tmp$$");     # $$ is our process id
  1569.  
  1570.     # process argument list of files along with any includes
  1571.  
  1572.     foreach $file (@ARGV) {
  1573.     process($file, 'fh00');
  1574.     }
  1575.  
  1576.     sub process {
  1577.     local($filename, $input) = @_;
  1578.     $input++;        # this is a string increment
  1579.     unless (open($input, $filename)) {
  1580.         print STDERR "Can't open $filename: $!\n";
  1581.         return;
  1582.     }
  1583.  
  1584.     while (<$input>) {        # note use of indirection
  1585.         if (/^#include "(.*)"/) {
  1586.         process($1, $input);
  1587.         next;
  1588.         }
  1589.         ...        # whatever
  1590.     }
  1591.     }
  1592.  
  1593. You may also, in the Bourne shell tradition, specify an EXPR beginning
  1594. with ">&", in which case the rest of the string is interpreted as the
  1595. name of a filehandle (or file descriptor, if numeric) which is to be
  1596. duped and opened.  You may use & after >, >>, <, +>, +>> and +<.  The
  1597. mode you specify should match the mode of the original filehandle.
  1598. Here is a script that saves, redirects, and restores STDOUT and
  1599. STDERR:
  1600.  
  1601.     #!/usr/bin/perl
  1602.     open(SAVEOUT, ">&STDOUT");
  1603.     open(SAVEERR, ">&STDERR");
  1604.  
  1605.     open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  1606.     open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  1607.  
  1608.     select(STDERR); $| = 1;    # make unbuffered
  1609.     select(STDOUT); $| = 1;    # make unbuffered
  1610.  
  1611.     print STDOUT "stdout 1\n";    # this works for
  1612.     print STDERR "stderr 1\n";     # subprocesses too
  1613.  
  1614.     close(STDOUT);
  1615.     close(STDERR);
  1616.  
  1617.     open(STDOUT, ">&SAVEOUT");
  1618.     open(STDERR, ">&SAVEERR");
  1619.  
  1620.     print STDOUT "stdout 2\n";
  1621.     print STDERR "stderr 2\n";
  1622.  
  1623.  
  1624. If you specify "<&=N", where N is a number, then Perl will do an
  1625. equivalent of C's fdopen() of that file descriptor.  For example:
  1626.  
  1627.     open(FILEHANDLE, "<&=$fd")
  1628.  
  1629. If you open a pipe on the command "-", i.e. either "|-" or "-|", then
  1630. there is an implicit fork done, and the return value of open is the pid
  1631. of the child within the parent process, and 0 within the child
  1632. process.  (Use defined($pid) to determine whether the open was successful.)
  1633. The filehandle behaves normally for the parent, but i/o to that
  1634. filehandle is piped from/to the STDOUT/STDIN of the child process.
  1635. In the child process the filehandle isn't opened--i/o happens from/to
  1636. the new STDOUT or STDIN.  Typically this is used like the normal
  1637. piped open when you want to exercise more control over just how the
  1638. pipe command gets executed, such as when you are running setuid, and
  1639. don't want to have to scan shell commands for metacharacters.  The
  1640. following pairs are more or less equivalent:
  1641.  
  1642.     open(FOO, "|tr '[a-z]' '[A-Z]'");
  1643.     open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
  1644.  
  1645.     open(FOO, "cat -n '$file'|");
  1646.     open(FOO, "-|") || exec 'cat', '-n', $file;
  1647.  
  1648. Explicitly closing any piped filehandle causes the parent process to
  1649. wait for the child to finish, and returns the status value in $?.
  1650. Note: on any operation which may do a fork, unflushed buffers remain
  1651. unflushed in both processes, which means you may need to set $| to
  1652. avoid duplicate output.
  1653.  
  1654. The filename that is passed to open will have leading and trailing
  1655. whitespace deleted.  In order to open a file with arbitrary weird
  1656. characters in it, it's necessary to protect any leading and trailing
  1657. whitespace thusly:
  1658.  
  1659.         $file =~ s#^(\s)#./$1#;
  1660.         open(FOO, "< $file\0");
  1661.  
  1662. =item opendir DIRHANDLE,EXPR
  1663.  
  1664. Opens a directory named EXPR for processing by readdir(), telldir(),
  1665. seekdir(), rewinddir() and closedir().  Returns TRUE if successful.
  1666. DIRHANDLEs have their own namespace separate from FILEHANDLEs.
  1667.  
  1668. =item ord EXPR
  1669.  
  1670. Returns the numeric ascii value of the first character of EXPR.  If
  1671. EXPR is omitted, uses $_.
  1672.  
  1673. =item pack TEMPLATE,LIST
  1674.  
  1675. Takes an array or list of values and packs it into a binary structure,
  1676. returning the string containing the structure.  The TEMPLATE is a
  1677. sequence of characters that give the order and type of values, as
  1678. follows:
  1679.  
  1680.     A    An ascii string, will be space padded.
  1681.     a    An ascii string, will be null padded.
  1682.     b    A bit string (ascending bit order, like vec()).
  1683.     B    A bit string (descending bit order).
  1684.     h    A hex string (low nybble first).
  1685.     H    A hex string (high nybble first).
  1686.  
  1687.     c    A signed char value.
  1688.     C    An unsigned char value.
  1689.     s    A signed short value.
  1690.     S    An unsigned short value.
  1691.     i    A signed integer value.
  1692.     I    An unsigned integer value.
  1693.     l    A signed long value.
  1694.     L    An unsigned long value.
  1695.  
  1696.     n    A short in "network" order.
  1697.     N    A long in "network" order.
  1698.     v    A short in "VAX" (little-endian) order.
  1699.     V    A long in "VAX" (little-endian) order.
  1700.  
  1701.     f    A single-precision float in the native format.
  1702.     d    A double-precision float in the native format.
  1703.  
  1704.     p    A pointer to a null-terminated string.
  1705.     P    A pointer to a structure (fixed-length string).
  1706.  
  1707.     u    A uuencoded string.
  1708.  
  1709.     x    A null byte.
  1710.     X    Back up a byte.
  1711.     @    Null fill to absolute position.
  1712.  
  1713. Each letter may optionally be followed by a number which gives a repeat
  1714. count.  With all types except "a", "A", "b", "B", "h" and "H", and "P" the
  1715. pack function will gobble up that many values from the LIST.  A * for the
  1716. repeat count means to use however many items are left.  The "a" and "A"
  1717. types gobble just one value, but pack it as a string of length count,
  1718. padding with nulls or spaces as necessary.  (When unpacking, "A" strips
  1719. trailing spaces and nulls, but "a" does not.)  Likewise, the "b" and "B"
  1720. fields pack a string that many bits long.  The "h" and "H" fields pack a
  1721. string that many nybbles long.  The "P" packs a pointer to a structure of
  1722. the size indicated by the length.  Real numbers (floats and doubles) are
  1723. in the native machine format only; due to the multiplicity of floating
  1724. formats around, and the lack of a standard "network" representation, no
  1725. facility for interchange has been made.  This means that packed floating
  1726. point data written on one machine may not be readable on another - even if
  1727. both use IEEE floating point arithmetic (as the endian-ness of the memory
  1728. representation is not part of the IEEE spec).  Note that Perl uses doubles
  1729. internally for all numeric calculation, and converting from double into
  1730. float and thence back to double again will lose precision (i.e.
  1731. C<unpack("f", pack("f", $foo)>) will not in general equal $foo).
  1732.  
  1733. Examples:
  1734.  
  1735.     $foo = pack("cccc",65,66,67,68);
  1736.     # foo eq "ABCD"
  1737.     $foo = pack("c4",65,66,67,68);
  1738.     # same thing
  1739.  
  1740.     $foo = pack("ccxxcc",65,66,67,68);
  1741.     # foo eq "AB\0\0CD"
  1742.  
  1743.     $foo = pack("s2",1,2);
  1744.     # "\1\0\2\0" on little-endian
  1745.     # "\0\1\0\2" on big-endian
  1746.  
  1747.     $foo = pack("a4","abcd","x","y","z");
  1748.     # "abcd"
  1749.  
  1750.     $foo = pack("aaaa","abcd","x","y","z");
  1751.     # "axyz"
  1752.  
  1753.     $foo = pack("a14","abcdefg");
  1754.     # "abcdefg\0\0\0\0\0\0\0"
  1755.  
  1756.     $foo = pack("i9pl", gmtime);
  1757.     # a real struct tm (on my system anyway)
  1758.  
  1759.     sub bintodec {
  1760.     unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  1761.     }
  1762.  
  1763. The same template may generally also be used in the unpack function.
  1764.  
  1765. =item pipe READHANDLE,WRITEHANDLE
  1766.  
  1767. Opens a pair of connected pipes like the corresponding system call.
  1768. Note that if you set up a loop of piped processes, deadlock can occur
  1769. unless you are very careful.  In addition, note that Perl's pipes use
  1770. stdio buffering, so you may need to set $| to flush your WRITEHANDLE
  1771. after each command, depending on the application.
  1772.  
  1773. =item pop ARRAY
  1774.  
  1775. Pops and returns the last value of the array, shortening the array by
  1776. 1.  Has a similar effect to
  1777.  
  1778.     $tmp = $ARRAY[$#ARRAY--];
  1779.  
  1780. If there are no elements in the array, returns the undefined value.
  1781.  
  1782. =item pos SCALAR
  1783.  
  1784. Returns the offset of where the last m//g search left off for the variable
  1785. in question.  May be modified to change that offset.
  1786.  
  1787. =item print FILEHANDLE LIST
  1788.  
  1789. =item print LIST
  1790.  
  1791. =item print
  1792.  
  1793. Prints a string or a comma-separated list of strings.  Returns non-zero
  1794. if successful.  FILEHANDLE may be a scalar variable name, in which case
  1795. the variable contains the name of the filehandle, thus introducing one
  1796. level of indirection.  (NOTE: If FILEHANDLE is a variable and the next
  1797. token is a term, it may be misinterpreted as an operator unless you
  1798. interpose a + or put parens around the arguments.)  If FILEHANDLE is
  1799. omitted, prints by default to standard output (or to the last selected
  1800. output channel--see select()).  If LIST is also omitted, prints $_ to
  1801. STDOUT.  To set the default output channel to something other than
  1802. STDOUT use the select operation.  Note that, because print takes a
  1803. LIST, anything in the LIST is evaluated in a list context, and any
  1804. subroutine that you call will have one or more of its expressions
  1805. evaluated in a list context.  Also be careful not to follow the print
  1806. keyword with a left parenthesis unless you want the corresponding right
  1807. parenthesis to terminate the arguments to the print--interpose a + or
  1808. put parens around all the arguments.
  1809.  
  1810. =item printf FILEHANDLE LIST
  1811.  
  1812. =item printf LIST
  1813.  
  1814. Equivalent to a "print FILEHANDLE sprintf(LIST)".  The first argument
  1815. of the list will be interpreted as the printf format.
  1816.  
  1817. =item push ARRAY,LIST
  1818.  
  1819. Treats ARRAY as a stack, and pushes the values of LIST
  1820. onto the end of ARRAY.  The length of ARRAY increases by the length of
  1821. LIST.  Has the same effect as
  1822.  
  1823.     for $value (LIST) {
  1824.     $ARRAY[++$#ARRAY] = $value;
  1825.     }
  1826.  
  1827. but is more efficient.  Returns the new number of elements in the array.
  1828.  
  1829. =item q/STRING/
  1830.  
  1831. =item qq/STRING/
  1832.  
  1833. =item qx/STRING/
  1834.  
  1835. =item qw/STRING/
  1836.  
  1837. Generalized quotes.  See L<perlop>.
  1838.  
  1839. =item quotemeta EXPR
  1840.  
  1841. Returns the value of EXPR with with all regular expression
  1842. metacharacters backslashed.  This is the internal function implementing
  1843. the \Q escape in double-quoted strings.
  1844.  
  1845. =item rand EXPR
  1846.  
  1847. =item rand
  1848.  
  1849. Returns a random fractional number between 0 and the value of EXPR.
  1850. (EXPR should be positive.)  If EXPR is omitted, returns a value between 
  1851. 0 and 1.  This function produces repeatable sequences unless srand() 
  1852. is invoked.  See also srand().
  1853.  
  1854. (Note: if your rand function consistently returns numbers that are too
  1855. large or too small, then your version of Perl was probably compiled
  1856. with the wrong number of RANDBITS.  As a workaround, you can usually
  1857. multiply EXPR by the correct power of 2 to get the range you want.
  1858. This will make your script unportable, however.  It's better to recompile
  1859. if you can.)
  1860.  
  1861. =item read FILEHANDLE,SCALAR,LENGTH,OFFSET
  1862.  
  1863. =item read FILEHANDLE,SCALAR,LENGTH
  1864.  
  1865. Attempts to read LENGTH bytes of data into variable SCALAR from the
  1866. specified FILEHANDLE.  Returns the number of bytes actually read, or
  1867. undef if there was an error.  SCALAR will be grown or shrunk to the
  1868. length actually read.  An OFFSET may be specified to place the read
  1869. data at some other place than the beginning of the string.  This call
  1870. is actually implemented in terms of stdio's fread call.  To get a true
  1871. read system call, see sysread().
  1872.  
  1873. =item readdir DIRHANDLE
  1874.  
  1875. Returns the next directory entry for a directory opened by opendir().
  1876. If used in a list context, returns all the rest of the entries in the
  1877. directory.  If there are no more entries, returns an undefined value in
  1878. a scalar context or a null list in a list context.
  1879.  
  1880. =item readlink EXPR
  1881.  
  1882. Returns the value of a symbolic link, if symbolic links are
  1883. implemented.  If not, gives a fatal error.  If there is some system
  1884. error, returns the undefined value and sets $! (errno).  If EXPR is
  1885. omitted, uses $_.
  1886.  
  1887. =item recv SOCKET,SCALAR,LEN,FLAGS
  1888.  
  1889. Receives a message on a socket.  Attempts to receive LENGTH bytes of
  1890. data into variable SCALAR from the specified SOCKET filehandle.
  1891. Actually does a C recvfrom(), so that it can returns the address of the
  1892. sender.  Returns the undefined value if there's an error.  SCALAR will
  1893. be grown or shrunk to the length actually read.  Takes the same flags
  1894. as the system call of the same name.
  1895.  
  1896. =item redo LABEL
  1897.  
  1898. =item redo
  1899.  
  1900. The C<redo> command restarts the loop block without evaluating the
  1901. conditional again.  The C<continue> block, if any, is not executed.  If
  1902. the LABEL is omitted, the command refers to the innermost enclosing
  1903. loop.  This command is normally used by programs that want to lie to
  1904. themselves about what was just input:
  1905.  
  1906.     # a simpleminded Pascal comment stripper
  1907.     # (warning: assumes no { or } in strings)
  1908.     line: while (<STDIN>) {
  1909.     while (s|({.*}.*){.*}|$1 |) {}
  1910.     s|{.*}| |;
  1911.     if (s|{.*| |) {
  1912.         $front = $_;
  1913.         while (<STDIN>) {
  1914.         if (/}/) {    # end of comment?
  1915.             s|^|$front{|;
  1916.             redo line;
  1917.         }
  1918.         }
  1919.     }
  1920.     print;
  1921.     }
  1922.  
  1923. =item ref EXPR
  1924.  
  1925. Returns a TRUE value if EXPR is a reference, FALSE otherwise.  The value
  1926. returned depends on the type of thing the reference is a reference to.
  1927. Builtin types include:
  1928.  
  1929.     REF
  1930.     SCALAR
  1931.     ARRAY
  1932.     HASH
  1933.     CODE
  1934.     GLOB
  1935.  
  1936. If the referenced object has been blessed into a package, then that package 
  1937. name is returned instead.  You can think of ref() as a typeof() operator.
  1938.  
  1939.     if (ref($r) eq "HASH") {
  1940.     print "r is a reference to an associative array.\n";
  1941.     } 
  1942.     if (!ref ($r) {
  1943.     print "r is not a reference at all.\n";
  1944.     } 
  1945.  
  1946. See also L<perlref>.
  1947.  
  1948. =item rename OLDNAME,NEWNAME
  1949.  
  1950. Changes the name of a file.  Returns 1 for success, 0 otherwise.  Will
  1951. not work across filesystem boundaries.
  1952.  
  1953. =item require EXPR
  1954.  
  1955. =item require
  1956.  
  1957. Demands some semantics specified by EXPR, or by $_ if EXPR is not
  1958. supplied.  If EXPR is numeric, demands that the current version of Perl
  1959. ($] or $PERL_VERSION) be equal or greater than EXPR.
  1960.  
  1961. Otherwise, demands that a library file be included if it hasn't already
  1962. been included.  The file is included via the do-FILE mechanism, which is
  1963. essentially just a variety of eval().  Has semantics similar to the following
  1964. subroutine:
  1965.  
  1966.     sub require {
  1967.     local($filename) = @_;
  1968.     return 1 if $INC{$filename};
  1969.     local($realfilename,$result);
  1970.     ITER: {
  1971.         foreach $prefix (@INC) {
  1972.         $realfilename = "$prefix/$filename";
  1973.         if (-f $realfilename) {
  1974.             $result = do $realfilename;
  1975.             last ITER;
  1976.         }
  1977.         }
  1978.         die "Can't find $filename in \@INC";
  1979.     }
  1980.     die $@ if $@;
  1981.     die "$filename did not return true value" unless $result;
  1982.     $INC{$filename} = $realfilename;
  1983.     $result;
  1984.     }
  1985.  
  1986. Note that the file will not be included twice under the same specified
  1987. name.  The file must return TRUE as the last statement to indicate
  1988. successful execution of any initialization code, so it's customary to
  1989. end such a file with "1;" unless you're sure it'll return TRUE
  1990. otherwise.  But it's better just to put the "C<1;>", in case you add more
  1991. statements.
  1992.  
  1993. If EXPR is a bare word, the require assumes a "F<.pm>" extension for you,
  1994. to make it easy to load standard modules.  This form of loading of 
  1995. modules does not risk altering your namespace.
  1996.  
  1997. For a yet-more-powerful import facility, see the L</use()> and 
  1998. L<perlmod>.
  1999.  
  2000. =item reset EXPR
  2001.  
  2002. =item reset
  2003.  
  2004. Generally used in a C<continue> block at the end of a loop to clear
  2005. variables and reset ?? searches so that they work again.  The
  2006. expression is interpreted as a list of single characters (hyphens
  2007. allowed for ranges).  All variables and arrays beginning with one of
  2008. those letters are reset to their pristine state.  If the expression is
  2009. omitted, one-match searches (?pattern?) are reset to match again.  Only
  2010. resets variables or searches in the current package.  Always returns
  2011. 1.  Examples:
  2012.  
  2013.     reset 'X';        # reset all X variables
  2014.     reset 'a-z';    # reset lower case variables
  2015.     reset;        # just reset ?? searches
  2016.  
  2017. Resetting "A-Z" is not recommended since you'll wipe out your
  2018. ARGV and ENV arrays.  Only resets package variables--lexical variables
  2019. are unaffected, but they clean themselves up on scope exit anyway,
  2020. so anymore you probably want to use them instead.  See L</my>.
  2021.  
  2022. =item return LIST
  2023.  
  2024. Returns from a subroutine or eval with the value specified.  (Note that
  2025. in the absence of a return a subroutine or eval will automatically
  2026. return the value of the last expression evaluated.)
  2027.  
  2028. =item reverse LIST
  2029.  
  2030. In a list context, returns a list value consisting of the elements
  2031. of LIST in the opposite order.  In a scalar context, returns a string
  2032. value consisting of the bytes of the first element of LIST in the
  2033. opposite order.
  2034.  
  2035. =item rewinddir DIRHANDLE
  2036.  
  2037. Sets the current position to the beginning of the directory for the
  2038. readdir() routine on DIRHANDLE.
  2039.  
  2040. =item rindex STR,SUBSTR,POSITION
  2041.  
  2042. =item rindex STR,SUBSTR
  2043.  
  2044. Works just like index except that it returns the position of the LAST
  2045. occurrence of SUBSTR in STR.  If POSITION is specified, returns the
  2046. last occurrence at or before that position.
  2047.  
  2048. =item rmdir FILENAME
  2049.  
  2050. Deletes the directory specified by FILENAME if it is empty.  If it
  2051. succeeds it returns 1, otherwise it returns 0 and sets $! (errno).  If
  2052. FILENAME is omitted, uses $_.
  2053.  
  2054. =item s///
  2055.  
  2056. The substitution operator.  See L<perlop>.
  2057.  
  2058. =item scalar EXPR
  2059.  
  2060. Forces EXPR to be interpreted in a scalar context and returns the value
  2061. of EXPR.
  2062.  
  2063. =item seek FILEHANDLE,POSITION,WHENCE
  2064.  
  2065. Randomly positions the file pointer for FILEHANDLE, just like the fseek()
  2066. call of stdio.  FILEHANDLE may be an expression whose value gives the name
  2067. of the filehandle.  The values for WHENCE are 0 to set the file pointer to
  2068. POSITION, 1 to set the it to current plus POSITION, and 2 to set it to EOF
  2069. plus offset.  You may use the values SEEK_SET, SEEK_CUR, and SEEK_END for
  2070. this is using the POSIX module.  Returns 1 upon success, 0 otherwise.
  2071.  
  2072. =item seekdir DIRHANDLE,POS
  2073.  
  2074. Sets the current position for the readdir() routine on DIRHANDLE.  POS
  2075. must be a value returned by telldir().  Has the same caveats about
  2076. possible directory compaction as the corresponding system library
  2077. routine.
  2078.  
  2079. =item select FILEHANDLE
  2080.  
  2081. =item select
  2082.  
  2083. Returns the currently selected filehandle.  Sets the current default
  2084. filehandle for output, if FILEHANDLE is supplied.  This has two
  2085. effects: first, a C<write> or a C<print> without a filehandle will
  2086. default to this FILEHANDLE.  Second, references to variables related to
  2087. output will refer to this output channel.  For example, if you have to
  2088. set the top of form format for more than one output channel, you might
  2089. do the following:
  2090.  
  2091.     select(REPORT1);
  2092.     $^ = 'report1_top';
  2093.     select(REPORT2);
  2094.     $^ = 'report2_top';
  2095.  
  2096. FILEHANDLE may be an expression whose value gives the name of the
  2097. actual filehandle.  Thus:
  2098.  
  2099.     $oldfh = select(STDERR); $| = 1; select($oldfh);
  2100.  
  2101. With Perl 5, filehandles are objects with methods, and the last example
  2102. is preferably written
  2103.  
  2104.     use FileHandle;
  2105.     STDERR->autoflush(1);
  2106.  
  2107. =item select RBITS,WBITS,EBITS,TIMEOUT
  2108.  
  2109. This calls the select system(2) call with the bitmasks specified, which
  2110. can be constructed using fileno() and vec(), along these lines:
  2111.  
  2112.     $rin = $win = $ein = '';
  2113.     vec($rin,fileno(STDIN),1) = 1;
  2114.     vec($win,fileno(STDOUT),1) = 1;
  2115.     $ein = $rin | $win;
  2116.  
  2117. If you want to select on many filehandles you might wish to write a
  2118. subroutine:
  2119.  
  2120.     sub fhbits {
  2121.     local(@fhlist) = split(' ',$_[0]);
  2122.     local($bits);
  2123.     for (@fhlist) {
  2124.         vec($bits,fileno($_),1) = 1;
  2125.     }
  2126.     $bits;
  2127.     }
  2128.     $rin = &fhbits('STDIN TTY SOCK');
  2129.  
  2130. The usual idiom is:
  2131.  
  2132.     ($nfound,$timeleft) =
  2133.       select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  2134.  
  2135. or to block until something becomes ready:
  2136.  
  2137.     $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
  2138.  
  2139. Any of the bitmasks can also be undef.  The timeout, if specified, is
  2140. in seconds, which may be fractional.  Note: not all implementations are
  2141. capable of returning the $timeleft.  If not, they always return
  2142. $timeleft equal to the supplied $timeout.
  2143.  
  2144. You can effect a 250 microsecond sleep this way:
  2145.  
  2146.     select(undef, undef, undef, 0.25);
  2147.  
  2148.  
  2149. =item semctl ID,SEMNUM,CMD,ARG
  2150.  
  2151. Calls the System V IPC function semctl.  If CMD is &IPC_STAT or
  2152. &GETALL, then ARG must be a variable which will hold the returned
  2153. semid_ds structure or semaphore value array.  Returns like ioctl: the
  2154. undefined value for error, "0 but true" for zero, or the actual return
  2155. value otherwise.
  2156.  
  2157. =item semget KEY,NSEMS,FLAGS
  2158.  
  2159. Calls the System V IPC function semget.  Returns the semaphore id, or
  2160. the undefined value if there is an error.
  2161.  
  2162. =item semop KEY,OPSTRING
  2163.  
  2164. Calls the System V IPC function semop to perform semaphore operations
  2165. such as signaling and waiting.  OPSTRING must be a packed array of
  2166. semop structures.  Each semop structure can be generated with
  2167. C<pack("sss", $semnum, $semop, $semflag)>.  The number of semaphore
  2168. operations is implied by the length of OPSTRING.  Returns TRUE if
  2169. successful, or FALSE if there is an error.  As an example, the
  2170. following code waits on semaphore $semnum of semaphore id $semid:
  2171.  
  2172.     $semop = pack("sss", $semnum, -1, 0);
  2173.     die "Semaphore trouble: $!\n" unless semop($semid, $semop);
  2174.  
  2175. To signal the semaphore, replace "-1" with "1".
  2176.  
  2177. =item send SOCKET,MSG,FLAGS,TO
  2178.  
  2179. =item send SOCKET,MSG,FLAGS
  2180.  
  2181. Sends a message on a socket.  Takes the same flags as the system call
  2182. of the same name.  On unconnected sockets you must specify a
  2183. destination to send TO, in which case it does a C sendto().  Returns
  2184. the number of characters sent, or the undefined value if there is an
  2185. error.
  2186.  
  2187. =item setpgrp PID,PGRP
  2188.  
  2189. Sets the current process group for the specified PID, 0 for the current
  2190. process.  Will produce a fatal error if used on a machine that doesn't
  2191. implement setpgrp(2).
  2192.  
  2193. =item setpriority WHICH,WHO,PRIORITY
  2194.  
  2195. Sets the current priority for a process, a process group, or a user.
  2196. (See setpriority(2).)  Will produce a fatal error if used on a machine
  2197. that doesn't implement setpriority(2).
  2198.  
  2199. =item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL
  2200.  
  2201. Sets the socket option requested.  Returns undefined if there is an
  2202. error.  OPTVAL may be specified as undef if you don't want to pass an
  2203. argument.
  2204.  
  2205. =item shift ARRAY
  2206.  
  2207. =item shift
  2208.  
  2209. Shifts the first value of the array off and returns it, shortening the
  2210. array by 1 and moving everything down.  If there are no elements in the
  2211. array, returns the undefined value.  If ARRAY is omitted, shifts the
  2212. @ARGV array in the main program, and the @_ array in subroutines.
  2213. (This is determined lexically.)  See also unshift(), push(), and pop().
  2214. Shift() and unshift() do the same thing to the left end of an array
  2215. that push() and pop() do to the right end.
  2216.  
  2217. =item shmctl ID,CMD,ARG
  2218.  
  2219. Calls the System V IPC function shmctl.  If CMD is &IPC_STAT, then ARG
  2220. must be a variable which will hold the returned shmid_ds structure.
  2221. Returns like ioctl: the undefined value for error, "0 but true" for
  2222. zero, or the actual return value otherwise.
  2223.  
  2224. =item shmget KEY,SIZE,FLAGS
  2225.  
  2226. Calls the System V IPC function shmget.  Returns the shared memory
  2227. segment id, or the undefined value if there is an error.
  2228.  
  2229. =item shmread ID,VAR,POS,SIZE
  2230.  
  2231. =item shmwrite ID,STRING,POS,SIZE
  2232.  
  2233. Reads or writes the System V shared memory segment ID starting at
  2234. position POS for size SIZE by attaching to it, copying in/out, and
  2235. detaching from it.  When reading, VAR must be a variable which will
  2236. hold the data read.  When writing, if STRING is too long, only SIZE
  2237. bytes are used; if STRING is too short, nulls are written to fill out
  2238. SIZE bytes.  Return TRUE if successful, or FALSE if there is an error.
  2239.  
  2240. =item shutdown SOCKET,HOW
  2241.  
  2242. Shuts down a socket connection in the manner indicated by HOW, which
  2243. has the same interpretation as in the system call of the same name.
  2244.  
  2245. =item sin EXPR
  2246.  
  2247. Returns the sine of EXPR (expressed in radians).  If EXPR is omitted,
  2248. returns sine of $_.
  2249.  
  2250. =item sleep EXPR
  2251.  
  2252. =item sleep
  2253.  
  2254. Causes the script to sleep for EXPR seconds, or forever if no EXPR.
  2255. May be interrupted by sending the process a SIGALRM.  Returns the
  2256. number of seconds actually slept.  You probably cannot mix alarm() and
  2257. sleep() calls, since sleep() is often implemented using alarm().
  2258.  
  2259. On some older systems, it may sleep up to a full second less than what
  2260. you requested, depending on how it counts seconds.  Most modern systems
  2261. always sleep the full amount.
  2262.  
  2263. =item socket SOCKET,DOMAIN,TYPE,PROTOCOL
  2264.  
  2265. Opens a socket of the specified kind and attaches it to filehandle
  2266. SOCKET.  DOMAIN, TYPE and PROTOCOL are specified the same as for the
  2267. system call of the same name.  You should "use Socket;" first to get
  2268. the proper definitions imported.  See the example in L<perlipc>.
  2269.  
  2270. =item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL
  2271.  
  2272. Creates an unnamed pair of sockets in the specified domain, of the
  2273. specified type.  DOMAIN, TYPE and PROTOCOL are specified the same as
  2274. for the system call of the same name.  If unimplemented, yields a fatal
  2275. error.  Returns TRUE if successful.
  2276.  
  2277. =item sort SUBNAME LIST
  2278.  
  2279. =item sort BLOCK LIST
  2280.  
  2281. =item sort LIST
  2282.  
  2283. Sorts the LIST and returns the sorted list value.  Nonexistent values
  2284. of arrays are stripped out.  If SUBNAME or BLOCK is omitted, sorts
  2285. in standard string comparison order.  If SUBNAME is specified, it
  2286. gives the name of a subroutine that returns an integer less than, equal
  2287. to, or greater than 0, depending on how the elements of the array are
  2288. to be ordered.  (The <=> and cmp operators are extremely useful in such
  2289. routines.)  SUBNAME may be a scalar variable name, in which case the
  2290. value provides the name of the subroutine to use.  In place of a
  2291. SUBNAME, you can provide a BLOCK as an anonymous, in-line sort
  2292. subroutine.
  2293.  
  2294. In the interests of efficiency the normal calling code for subroutines
  2295. is bypassed, with the following effects: the subroutine may not be a
  2296. recursive subroutine, and the two elements to be compared are passed
  2297. into the subroutine not via @_ but as $a and $b (see example below).
  2298. They are passed by reference, so don't modify $a and $b.
  2299.  
  2300. Examples:
  2301.  
  2302.     # sort lexically
  2303.     @articles = sort @files;
  2304.  
  2305.     # same thing, but with explicit sort routine
  2306.     @articles = sort {$a cmp $b} @files;
  2307.  
  2308.     # same thing in reversed order
  2309.     @articles = sort {$b cmp $a} @files;
  2310.  
  2311.     # sort numerically ascending
  2312.     @articles = sort {$a <=> $b} @files;
  2313.  
  2314.     # sort numerically descending
  2315.     @articles = sort {$b <=> $a} @files;
  2316.  
  2317.     # sort using explicit subroutine name
  2318.     sub byage {
  2319.     $age{$a} <=> $age{$b};    # presuming integers
  2320.     }
  2321.     @sortedclass = sort byage @class;
  2322.  
  2323.     sub backwards { $b cmp $a; }
  2324.     @harry = ('dog','cat','x','Cain','Abel');
  2325.     @george = ('gone','chased','yz','Punished','Axed');
  2326.     print sort @harry;
  2327.         # prints AbelCaincatdogx
  2328.     print sort backwards @harry;
  2329.         # prints xdogcatCainAbel
  2330.     print sort @george, 'to', @harry;
  2331.         # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  2332.  
  2333. =item splice ARRAY,OFFSET,LENGTH,LIST
  2334.  
  2335. =item splice ARRAY,OFFSET,LENGTH
  2336.  
  2337. =item splice ARRAY,OFFSET
  2338.  
  2339. Removes the elements designated by OFFSET and LENGTH from an array, and
  2340. replaces them with the elements of LIST, if any.  Returns the elements
  2341. removed from the array.  The array grows or shrinks as necessary.  If
  2342. LENGTH is omitted, removes everything from OFFSET onward.  The
  2343. following equivalencies hold (assuming $[ == 0):
  2344.  
  2345.     push(@a,$x,$y)    splice(@a,$#a+1,0,$x,$y)
  2346.     pop(@a)        splice(@a,-1)
  2347.     shift(@a)        splice(@a,0,1)
  2348.     unshift(@a,$x,$y)    splice(@a,0,0,$x,$y)
  2349.     $a[$x] = $y        splice(@a,$x,1,$y);
  2350.  
  2351. Example, assuming array lengths are passed before arrays:
  2352.  
  2353.     sub aeq {    # compare two list values
  2354.     local(@a) = splice(@_,0,shift);
  2355.     local(@b) = splice(@_,0,shift);
  2356.     return 0 unless @a == @b;    # same len?
  2357.     while (@a) {
  2358.         return 0 if pop(@a) ne pop(@b);
  2359.     }
  2360.     return 1;
  2361.     }
  2362.     if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  2363.  
  2364. =item split /PATTERN/,EXPR,LIMIT
  2365.  
  2366. =item split /PATTERN/,EXPR
  2367.  
  2368. =item split /PATTERN/
  2369.  
  2370. =item split
  2371.  
  2372. Splits a string into an array of strings, and returns it.
  2373.  
  2374. If not in a list context, returns the number of fields found and splits into
  2375. the @_ array.  (In a list context, you can force the split into @_ by
  2376. using C<??> as the pattern delimiters, but it still returns the array
  2377. value.)  The use of implicit split to @_ is deprecated, however.
  2378.  
  2379. If EXPR is omitted, splits the $_ string.  If PATTERN is also omitted,
  2380. splits on whitespace (after skipping any leading whitespace).
  2381. Anything matching PATTERN is taken
  2382. to be a delimiter separating the fields.  (Note that the delimiter may
  2383. be longer than one character.)  If LIMIT is specified and is not
  2384. negative, splits into no more than that many fields (though it may
  2385. split into fewer).  If LIMIT is unspecified, trailing null fields are
  2386. stripped (which potential users of pop() would do well to remember).
  2387. If LIMIT is negative, it is treated as if an arbitrarily large LIMIT
  2388. had been specified.
  2389.  
  2390. A pattern matching the null string (not to be confused with
  2391. a null pattern C<//>, which is just one member of the set of patterns
  2392. matching a null string) will split the value of EXPR into separate
  2393. characters at each point it matches that way.  For example:
  2394.  
  2395.     print join(':', split(/ */, 'hi there'));
  2396.  
  2397. produces the output 'h:i:t:h:e:r:e'.
  2398.  
  2399. The LIMIT parameter can be used to partially split a line
  2400.  
  2401.     ($login, $passwd, $remainder) = split(/:/, $_, 3);
  2402.  
  2403. When assigning to a list, if LIMIT is omitted, Perl supplies a LIMIT
  2404. one larger than the number of variables in the list, to avoid
  2405. unnecessary work.  For the list above LIMIT would have been 4 by
  2406. default.  In time critical applications it behooves you not to split
  2407. into more fields than you really need.
  2408.  
  2409. If the PATTERN contains parentheses, additional array elements are
  2410. created from each matching substring in the delimiter.
  2411.  
  2412.     split(/([,-])/, "1-10,20");
  2413.  
  2414. produces the list value
  2415.  
  2416.     (1, '-', 10, ',', 20)
  2417.  
  2418. The pattern C</PATTERN/> may be replaced with an expression to specify
  2419. patterns that vary at runtime.  (To do runtime compilation only once,
  2420. use C</$variable/o>.)
  2421.  
  2422. As a special case, specifying a PATTERN of space (C<' '>) will split on
  2423. white space just as split with no arguments does.  Thus, split(' ') can
  2424. be used to emulate B<awk>'s default behavior, whereas C<split(/ /)>
  2425. will give you as many null initial fields as there are leading spaces.
  2426. A split on /\s+/ is like a split(' ') except that any leading
  2427. whitespace produces a null first field.  A split with no arguments
  2428. really does a C<split(' ', $_)> internally.
  2429.  
  2430. Example:
  2431.  
  2432.     open(passwd, '/etc/passwd');
  2433.     while (<passwd>) {
  2434.     ($login, $passwd, $uid, $gid, $gcos, 
  2435.         $home, $shell) = split(/:/);
  2436.     ...
  2437.     }
  2438.  
  2439. (Note that $shell above will still have a newline on it.  See L</chop>, 
  2440. L</chomp>, and L</join>.)
  2441.  
  2442. =item sprintf FORMAT,LIST
  2443.  
  2444. Returns a string formatted by the usual printf conventions of the C
  2445. language.  (The * character for an indirectly specified length is not
  2446. supported, but you can get the same effect by interpolating a variable
  2447. into the pattern.)
  2448.  
  2449. =item sqrt EXPR
  2450.  
  2451. Return the square root of EXPR.  If EXPR is omitted, returns square
  2452. root of $_.
  2453.  
  2454. =item srand EXPR
  2455.  
  2456. Sets the random number seed for the C<rand> operator.  If EXPR is
  2457. omitted, does C<srand(time)>.  Of course, you'd need something much more
  2458. random than that for cryptographic purposes, since it's easy to guess
  2459. the current time.  Checksumming the compressed output of rapidly
  2460. changing operating system status programs is the usual method.
  2461. Examples are posted regularly to comp.security.unix.
  2462.  
  2463. =item stat FILEHANDLE
  2464.  
  2465. =item stat EXPR
  2466.  
  2467. Returns a 13-element array giving the status info for a file, either the
  2468. file opened via FILEHANDLE, or named by EXPR.  Returns a null list if
  2469. the stat fails.  Typically used as follows:
  2470.  
  2471.     ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  2472.        $atime,$mtime,$ctime,$blksize,$blocks)
  2473.            = stat($filename);
  2474.  
  2475. If stat is passed the special filehandle consisting of an underline, no
  2476. stat is done, but the current contents of the stat structure from the
  2477. last stat or filetest are returned.  Example:
  2478.  
  2479.     if (-x $file && (($d) = stat(_)) && $d < 0) {
  2480.     print "$file is executable NFS file\n";
  2481.     }
  2482.  
  2483. (This only works on machines for which the device number is negative under NFS.)
  2484.  
  2485. =item study SCALAR
  2486.  
  2487. =item study
  2488.  
  2489. Takes extra time to study SCALAR ($_ if unspecified) in anticipation of
  2490. doing many pattern matches on the string before it is next modified.
  2491. This may or may not save time, depending on the nature and number of
  2492. patterns you are searching on, and on the distribution of character
  2493. frequencies in the string to be searched--you probably want to compare
  2494. runtimes with and without it to see which runs faster.  Those loops
  2495. which scan for many short constant strings (including the constant
  2496. parts of more complex patterns) will benefit most.  You may have only
  2497. one study active at a time--if you study a different scalar the first
  2498. is "unstudied".  (The way study works is this: a linked list of every
  2499. character in the string to be searched is made, so we know, for
  2500. example, where all the 'k' characters are.  From each search string,
  2501. the rarest character is selected, based on some static frequency tables
  2502. constructed from some C programs and English text.  Only those places
  2503. that contain this "rarest" character are examined.)
  2504.  
  2505. For example, here is a loop which inserts index producing entries
  2506. before any line containing a certain pattern:
  2507.  
  2508.     while (<>) {
  2509.     study;
  2510.     print ".IX foo\n" if /\bfoo\b/;
  2511.     print ".IX bar\n" if /\bbar\b/;
  2512.     print ".IX blurfl\n" if /\bblurfl\b/;
  2513.     ...
  2514.     print;
  2515.     }
  2516.  
  2517. In searching for /\bfoo\b/, only those locations in $_ that contain "f"
  2518. will be looked at, because "f" is rarer than "o".  In general, this is
  2519. a big win except in pathological cases.  The only question is whether
  2520. it saves you more time than it took to build the linked list in the
  2521. first place.
  2522.  
  2523. Note that if you have to look for strings that you don't know till
  2524. runtime, you can build an entire loop as a string and eval that to
  2525. avoid recompiling all your patterns all the time.  Together with
  2526. undefining $/ to input entire files as one record, this can be very
  2527. fast, often faster than specialized programs like fgrep(1).  The following
  2528. scans a list of files (@files) for a list of words (@words), and prints
  2529. out the names of those files that contain a match:
  2530.  
  2531.     $search = 'while (<>) { study;';
  2532.     foreach $word (@words) {
  2533.     $search .= "++\$seen{\$ARGV} if /\\b$word\\b/;\n";
  2534.     }
  2535.     $search .= "}";
  2536.     @ARGV = @files;
  2537.     undef $/;
  2538.     eval $search;        # this screams
  2539.     $/ = "\n";        # put back to normal input delim
  2540.     foreach $file (sort keys(%seen)) {
  2541.     print $file, "\n";
  2542.     }
  2543.  
  2544. =item substr EXPR,OFFSET,LEN
  2545.  
  2546. =item substr EXPR,OFFSET
  2547.  
  2548. Extracts a substring out of EXPR and returns it.  First character is at
  2549. offset 0, or whatever you've set $[ to.  If OFFSET is negative, starts
  2550. that far from the end of the string.  If LEN is omitted, returns
  2551. everything to the end of the string.  If LEN is negative, leaves that
  2552. many characters off the end of the string.
  2553.  
  2554. You can use the substr() function
  2555. as an lvalue, in which case EXPR must be an lvalue.  If you assign
  2556. something shorter than LEN, the string will shrink, and if you assign
  2557. something longer than LEN, the string will grow to accommodate it.  To
  2558. keep the string the same length you may need to pad or chop your value
  2559. using sprintf().
  2560.  
  2561. =item symlink OLDFILE,NEWFILE
  2562.  
  2563. Creates a new filename symbolically linked to the old filename.
  2564. Returns 1 for success, 0 otherwise.  On systems that don't support
  2565. symbolic links, produces a fatal error at run time.  To check for that,
  2566. use eval:
  2567.  
  2568.     $symlink_exists = (eval 'symlink("","");', $@ eq '');
  2569.  
  2570. =item syscall LIST
  2571.  
  2572. Calls the system call specified as the first element of the list,
  2573. passing the remaining elements as arguments to the system call.  If
  2574. unimplemented, produces a fatal error.  The arguments are interpreted
  2575. as follows: if a given argument is numeric, the argument is passed as
  2576. an int.  If not, the pointer to the string value is passed.  You are
  2577. responsible to make sure a string is pre-extended long enough to
  2578. receive any result that might be written into a string.  If your
  2579. integer arguments are not literals and have never been interpreted in a
  2580. numeric context, you may need to add 0 to them to force them to look
  2581. like numbers.
  2582.  
  2583.     require 'syscall.ph';        # may need to run h2ph
  2584.     syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9);
  2585.  
  2586. Note that Perl only supports passing of up to 14 arguments to your system call,
  2587. which in practice should usually suffice.
  2588.  
  2589. =item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
  2590.  
  2591. =item sysread FILEHANDLE,SCALAR,LENGTH
  2592.  
  2593. Attempts to read LENGTH bytes of data into variable SCALAR from the
  2594. specified FILEHANDLE, using the system call read(2).  It bypasses
  2595. stdio, so mixing this with other kinds of reads may cause confusion.
  2596. Returns the number of bytes actually read, or undef if there was an
  2597. error.  SCALAR will be grown or shrunk to the length actually read.  An
  2598. OFFSET may be specified to place the read data at some other place than
  2599. the beginning of the string.
  2600.  
  2601. =item system LIST
  2602.  
  2603. Does exactly the same thing as "exec LIST" except that a fork is done
  2604. first, and the parent process waits for the child process to complete.
  2605. Note that argument processing varies depending on the number of
  2606. arguments.  The return value is the exit status of the program as
  2607. returned by the wait() call.  To get the actual exit value divide by
  2608. 256.  See also L</exec>.
  2609.  
  2610. =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
  2611.  
  2612. =item syswrite FILEHANDLE,SCALAR,LENGTH
  2613.  
  2614. Attempts to write LENGTH bytes of data from variable SCALAR to the
  2615. specified FILEHANDLE, using the system call write(2).  It bypasses
  2616. stdio, so mixing this with prints may cause confusion.  Returns the
  2617. number of bytes actually written, or undef if there was an error.  An
  2618. OFFSET may be specified to place the read data at some other place than
  2619. the beginning of the string.
  2620.  
  2621. =item tell FILEHANDLE
  2622.  
  2623. =item tell
  2624.  
  2625. Returns the current file position for FILEHANDLE.  FILEHANDLE may be an
  2626. expression whose value gives the name of the actual filehandle.  If
  2627. FILEHANDLE is omitted, assumes the file last read.
  2628.  
  2629. =item telldir DIRHANDLE
  2630.  
  2631. Returns the current position of the readdir() routines on DIRHANDLE.
  2632. Value may be given to seekdir() to access a particular location in a
  2633. directory.  Has the same caveats about possible directory compaction as
  2634. the corresponding system library routine.
  2635.  
  2636. =item tie VARIABLE,PACKAGENAME,LIST
  2637.  
  2638. This function binds a variable to a package that will provide the
  2639. implementation for the variable.  VARIABLE is the name of the variable to
  2640. be enchanted.  PACKAGENAME is the name of a package implementing objects
  2641. of correct type.  Any additional arguments are passed to the "new" method
  2642. of the package (meaning TIESCALAR, TIEARRAY, or TIEHASH).  Typically these
  2643. are arguments such as might be passed to the dbm_open() function of C.
  2644.  
  2645. Note that functions such as keys() and values() may return huge array
  2646. values when used on large objects, like DBM files.  You may prefer to
  2647. use the each() function to iterate over such.  Example:
  2648.  
  2649.     # print out history file offsets
  2650.     tie(%HIST, NDBM_File, '/usr/lib/news/history', 1, 0);
  2651.     while (($key,$val) = each %HIST) {
  2652.     print $key, ' = ', unpack('L',$val), "\n";
  2653.     }
  2654.     untie(%HIST);
  2655.  
  2656. A package implementing an associative array should have the following
  2657. methods:
  2658.  
  2659.     TIEHASH objectname, LIST
  2660.     DESTROY this
  2661.     FETCH this, key
  2662.     STORE this, key, value
  2663.     DELETE this, key
  2664.     EXISTS this, key
  2665.     FIRSTKEY this
  2666.     NEXTKEY this, lastkey
  2667.  
  2668. A package implementing an ordinary array should have the following methods:
  2669.  
  2670.     TIEARRAY objectname, LIST
  2671.     DESTROY this
  2672.     FETCH this, key
  2673.     STORE this, key, value
  2674.     [others TBD]
  2675.  
  2676. A package implementing a scalar should have the following methods:
  2677.  
  2678.     TIESCALAR objectname, LIST
  2679.     DESTROY this
  2680.     FETCH this, 
  2681.     STORE this, value
  2682.  
  2683. =item time
  2684.  
  2685. Returns the number of non-leap seconds since 00:00:00 UTC, January 1,
  2686. 1970.  Suitable for feeding to gmtime() and localtime().
  2687.  
  2688. =item times
  2689.  
  2690. Returns a four-element array giving the user and system times, in
  2691. seconds, for this process and the children of this process.
  2692.  
  2693.     ($user,$system,$cuser,$csystem) = times;
  2694.  
  2695. =item tr///
  2696.  
  2697. The translation operator.  See L<perlop>.
  2698.  
  2699. =item truncate FILEHANDLE,LENGTH
  2700.  
  2701. =item truncate EXPR,LENGTH
  2702.  
  2703. Truncates the file opened on FILEHANDLE, or named by EXPR, to the
  2704. specified length.  Produces a fatal error if truncate isn't implemented
  2705. on your system.
  2706.  
  2707. =item uc EXPR
  2708.  
  2709. Returns an uppercased version of EXPR.  This is the internal function
  2710. implementing the \U escape in double-quoted strings.
  2711.  
  2712. =item ucfirst EXPR
  2713.  
  2714. Returns the value of EXPR with the first character uppercased.  This is
  2715. the internal function implementing the \u escape in double-quoted strings.
  2716.  
  2717. =item umask EXPR
  2718.  
  2719. =item umask
  2720.  
  2721. Sets the umask for the process and returns the old one.  If EXPR is
  2722. omitted, merely returns current umask.
  2723.  
  2724. =item undef EXPR
  2725.  
  2726. =item undef
  2727.  
  2728. Undefines the value of EXPR, which must be an lvalue.  Use only on a
  2729. scalar value, an entire array, or a subroutine name (using "&").  (Using undef()
  2730. will probably not do what you expect on most predefined variables or
  2731. DBM list values, so don't do that.)  Always returns the undefined value.  You can omit
  2732. the EXPR, in which case nothing is undefined, but you still get an
  2733. undefined value that you could, for instance, return from a
  2734. subroutine.  Examples:
  2735.  
  2736.     undef $foo;
  2737.     undef $bar{'blurfl'};
  2738.     undef @ary;
  2739.     undef %assoc;
  2740.     undef &mysub;
  2741.     return (wantarray ? () : undef) if $they_blew_it;
  2742.  
  2743. =item unlink LIST
  2744.  
  2745. Deletes a list of files.  Returns the number of files successfully
  2746. deleted.
  2747.  
  2748.     $cnt = unlink 'a', 'b', 'c';
  2749.     unlink @goners;
  2750.     unlink <*.bak>;
  2751.  
  2752. Note: unlink will not delete directories unless you are superuser and
  2753. the B<-U> flag is supplied to Perl.  Even if these conditions are
  2754. met, be warned that unlinking a directory can inflict damage on your
  2755. filesystem.  Use rmdir instead.
  2756.  
  2757. =item unpack TEMPLATE,EXPR
  2758.  
  2759. Unpack does the reverse of pack: it takes a string representing a
  2760. structure and expands it out into a list value, returning the array
  2761. value.  (In a scalar context, it merely returns the first value
  2762. produced.)  The TEMPLATE has the same format as in the pack function.
  2763. Here's a subroutine that does substring:
  2764.  
  2765.     sub substr {
  2766.     local($what,$where,$howmuch) = @_;
  2767.     unpack("x$where a$howmuch", $what);
  2768.     }
  2769.  
  2770. and then there's
  2771.  
  2772.     sub ordinal { unpack("c",$_[0]); } # same as ord()
  2773.  
  2774. In addition, you may prefix a field with a %<number> to indicate that
  2775. you want a <number>-bit checksum of the items instead of the items
  2776. themselves.  Default is a 16-bit checksum.  For example, the following
  2777. computes the same number as the System V sum program:
  2778.  
  2779.     while (<>) {
  2780.     $checksum += unpack("%16C*", $_);
  2781.     }
  2782.     $checksum %= 65536;
  2783.  
  2784. The following efficiently counts the number of set bits in a bit vector:
  2785.  
  2786.     $setbits = unpack("%32b*", $selectmask);
  2787.  
  2788. =item untie VARIABLE
  2789.  
  2790. Breaks the binding between a variable and a package.  (See tie().)
  2791.  
  2792. =item unshift ARRAY,LIST
  2793.  
  2794. Does the opposite of a C<shift>.  Or the opposite of a C<push>,
  2795. depending on how you look at it.  Prepends list to the front of the
  2796. array, and returns the new number of elements in the array.
  2797.  
  2798.     unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;
  2799.  
  2800. Note the LIST is prepended whole, not one element at a time, so the
  2801. prepended elements stay in the same order.  Use reverse to do the
  2802. reverse.
  2803.  
  2804. =item use Module LIST
  2805.  
  2806. =item use Module
  2807.  
  2808. Imports some semantics into the current package from the named module,
  2809. generally by aliasing certain subroutine or variable names into your
  2810. package.  It is exactly equivalent to
  2811.  
  2812.     BEGIN { require Module; import Module LIST; }
  2813.  
  2814. If you don't want your namespace altered, use require instead.
  2815.  
  2816. The BEGIN forces the require and import to happen at compile time.  The
  2817. require makes sure the module is loaded into memory if it hasn't been
  2818. yet.  The import is not a builtin--it's just an ordinary static method
  2819. call into the "Module" package to tell the module to import the list of
  2820. features back into the current package.  The module can implement its
  2821. import method any way it likes, though most modules just choose to
  2822. derive their import method via inheritance from the Exporter class that
  2823. is defined in the Exporter module.
  2824.  
  2825. Because this is a wide-open interface, pragmas (compiler directives)
  2826. are also implemented this way.  Currently implemented pragmas are:
  2827.  
  2828.     use integer;
  2829.     use sigtrap qw(SEGV BUS);
  2830.     use strict  qw(subs vars refs);
  2831.     use subs    qw(afunc blurfl);
  2832.  
  2833. These pseudomodules import semantics into the current block scope, unlike
  2834. ordinary modules, which import symbols into the current package (which are
  2835. effective through the end of the file).
  2836.  
  2837. There's a corresponding "no" command that unimports meanings imported
  2838. by use.
  2839.  
  2840.     no integer;
  2841.     no strict 'refs';
  2842.  
  2843. See L<perlmod> for a list of standard modules and pragmas.
  2844.  
  2845. =item utime LIST
  2846.  
  2847. Changes the access and modification times on each file of a list of
  2848. files.  The first two elements of the list must be the NUMERICAL access
  2849. and modification times, in that order.  Returns the number of files
  2850. successfully changed.  The inode modification time of each file is set
  2851. to the current time.  Example of a "touch" command:
  2852.  
  2853.     #!/usr/bin/perl
  2854.     $now = time;
  2855.     utime $now, $now, @ARGV;
  2856.  
  2857. =item values ASSOC_ARRAY
  2858.  
  2859. Returns a normal array consisting of all the values of the named
  2860. associative array.  (In a scalar context, returns the number of
  2861. values.)  The values are returned in an apparently random order, but it
  2862. is the same order as either the keys() or each() function would produce
  2863. on the same array.  See also keys() and each().
  2864.  
  2865. =item vec EXPR,OFFSET,BITS
  2866.  
  2867. Treats a string as a vector of unsigned integers, and returns the value
  2868. of the bitfield specified.  May also be assigned to.  BITS must be a
  2869. power of two from 1 to 32.
  2870.  
  2871. Vectors created with vec() can also be manipulated with the logical
  2872. operators |, & and ^, which will assume a bit vector operation is
  2873. desired when both operands are strings.
  2874.  
  2875. To transform a bit vector into a string or array of 0's and 1's, use these:
  2876.  
  2877.     $bits = unpack("b*", $vector);
  2878.     @bits = split(//, unpack("b*", $vector));
  2879.  
  2880. If you know the exact length in bits, it can be used in place of the *.
  2881.  
  2882. =item wait
  2883.  
  2884. Waits for a child process to terminate and returns the pid of the
  2885. deceased process, or -1 if there are no child processes.  The status is
  2886. returned in $?.
  2887.  
  2888. =item waitpid PID,FLAGS
  2889.  
  2890. Waits for a particular child process to terminate and returns the pid
  2891. of the deceased process, or -1 if there is no such child process.  The
  2892. status is returned in $?.  If you say
  2893.  
  2894.     use POSIX "wait_h";
  2895.     ...
  2896.     waitpid(-1,&WNOHANG);
  2897.  
  2898. then you can do a non-blocking wait for any process.  Non-blocking wait
  2899. is only available on machines supporting either the waitpid(2) or
  2900. wait4(2) system calls.  However, waiting for a particular pid with
  2901. FLAGS of 0 is implemented everywhere.  (Perl emulates the system call
  2902. by remembering the status values of processes that have exited but have
  2903. not been harvested by the Perl script yet.)
  2904.  
  2905. =item wantarray
  2906.  
  2907. Returns TRUE if the context of the currently executing subroutine is
  2908. looking for a list value.  Returns FALSE if the context is looking
  2909. for a scalar.
  2910.  
  2911.     return wantarray ? () : undef;
  2912.  
  2913. =item warn LIST
  2914.  
  2915. Produces a message on STDERR just like die(), but doesn't exit or
  2916. throw an exception.
  2917.  
  2918. =item write FILEHANDLE
  2919.  
  2920. =item write EXPR
  2921.  
  2922. =item write
  2923.  
  2924. Writes a formatted record (possibly multi-line) to the specified file,
  2925. using the format associated with that file.  By default the format for
  2926. a file is the one having the same name is the filehandle, but the
  2927. format for the current output channel (see the select() function) may be set
  2928. explicitly by assigning the name of the format to the $~ variable.
  2929.  
  2930. Top of form processing is handled automatically:  if there is
  2931. insufficient room on the current page for the formatted record, the
  2932. page is advanced by writing a form feed, a special top-of-page format
  2933. is used to format the new page header, and then the record is written.
  2934. By default the top-of-page format is the name of the filehandle with
  2935. "_TOP" appended, but it may be dynamically set to the format of your
  2936. choice by assigning the name to the $^ variable while the filehandle is
  2937. selected.  The number of lines remaining on the current page is in
  2938. variable $-, which can be set to 0 to force a new page.
  2939.  
  2940. If FILEHANDLE is unspecified, output goes to the current default output
  2941. channel, which starts out as STDOUT but may be changed by the
  2942. C<select> operator.  If the FILEHANDLE is an EXPR, then the expression
  2943. is evaluated and the resulting string is used to look up the name of
  2944. the FILEHANDLE at run time.  For more on formats, see L<perlform>.
  2945.  
  2946. Note that write is I<NOT> the opposite of read.  Unfortunately.
  2947.  
  2948. =item y///
  2949.  
  2950. The translation operator.  See L<perlop/tr///>.
  2951.  
  2952. =back
  2953.