home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 2 / RISC_DISC_2.iso / pd_share / utilities / cli / perl / !Perl / Manual / perlfunc < prev    next >
Encoding:
Text File  |  1995-04-18  |  117.1 KB  |  3,195 lines

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