home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume18 / perl / part08 < prev    next >
Encoding:
Internet Message Format  |  1991-04-15  |  50.2 KB

  1. From: lwall@netlabs.com (Larry Wall)
  2. Newsgroups: comp.sources.misc
  3. Subject: v18i026:  perl - The perl programming language, Part08/36
  4. Message-ID: <1991Apr15.235927.22609@sparky.IMD.Sterling.COM>
  5. Date: 15 Apr 91 23:59:27 GMT
  6. Approved: kent@sparky.imd.sterling.com
  7. X-Checksum-Snefru: 51df451e 07043afb f52ef98d d2b4c999
  8.  
  9. Submitted-by: Larry Wall <lwall@netlabs.com>
  10. Posting-number: Volume 18, Issue 26
  11. Archive-name: perl/part08
  12.  
  13. [There are 36 kits for perl version 4.0.]
  14.  
  15. #! /bin/sh
  16.  
  17. # Make a new directory for the perl sources, cd to it, and run kits 1
  18. # thru 36 through sh.  When all 36 kits have been run, read README.
  19.  
  20. echo "This is perl 4.0 kit 8 (of 36).  If kit 8 is complete, the line"
  21. echo '"'"End of kit 8 (of 36)"'" will echo at the end.'
  22. echo ""
  23. export PATH || (echo "You didn't use sh, you clunch." ; kill $$)
  24. mkdir  2>/dev/null
  25. echo Extracting perl.man:AC
  26. sed >perl.man:AC <<'!STUFFY!FUNK!' -e 's/X//'
  27. Xpadding with nulls or spaces as necessary.
  28. X(When unpacking, "A" strips trailing spaces and nulls, but "a" does not.)
  29. XLikewise, the "b" and "B" fields pack a string that many bits long.
  30. XThe "h" and "H" fields pack a string that many nybbles long.
  31. XReal numbers (floats and doubles) are in the native machine format
  32. Xonly; due to the multiplicity of floating formats around, and the lack
  33. Xof a standard \*(L"network\*(R" representation, no facility for
  34. Xinterchange has been made.
  35. XThis means that packed floating point data
  36. Xwritten on one machine may not be readable on another - even if both
  37. Xuse IEEE floating point arithmetic (as the endian-ness of the memory
  38. Xrepresentation is not part of the IEEE spec).
  39. XNote that perl uses
  40. Xdoubles internally for all numeric calculation, and converting from
  41. Xdouble -> float -> double will lose precision (i.e. unpack("f",
  42. Xpack("f", $foo)) will not in general equal $foo).
  43. X.br
  44. XExamples:
  45. X.nf
  46. X
  47. X    $foo = pack("cccc",65,66,67,68);
  48. X    # foo eq "ABCD"
  49. X    $foo = pack("c4",65,66,67,68);
  50. X    # same thing
  51. X
  52. X    $foo = pack("ccxxcc",65,66,67,68);
  53. X    # foo eq "AB\e0\e0CD"
  54. X
  55. X    $foo = pack("s2",1,2);
  56. X    # "\e1\e0\e2\e0" on little-endian
  57. X    # "\e0\e1\e0\e2" on big-endian
  58. X
  59. X    $foo = pack("a4","abcd","x","y","z");
  60. X    # "abcd"
  61. X
  62. X    $foo = pack("aaaa","abcd","x","y","z");
  63. X    # "axyz"
  64. X
  65. X    $foo = pack("a14","abcdefg");
  66. X    # "abcdefg\e0\e0\e0\e0\e0\e0\e0"
  67. X
  68. X    $foo = pack("i9pl", gmtime);
  69. X    # a real struct tm (on my system anyway)
  70. X
  71. X    sub bintodec {
  72. X        unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  73. X    }
  74. X.fi
  75. XThe same template may generally also be used in the unpack function.
  76. X.Ip "pipe(READHANDLE,WRITEHANDLE)" 8 3
  77. XOpens a pair of connected pipes like the corresponding system call.
  78. XNote that if you set up a loop of piped processes, deadlock can occur
  79. Xunless you are very careful.
  80. XIn addition, note that perl's pipes use stdio buffering, so you may need
  81. Xto set $| to flush your WRITEHANDLE after each command, depending on
  82. Xthe application.
  83. X[Requires version 3.0 patchlevel 9.]
  84. X.Ip "pop(ARRAY)" 8
  85. X.Ip "pop ARRAY" 8 6
  86. XPops and returns the last value of the array, shortening the array by 1.
  87. XHas the same effect as
  88. X.nf
  89. X
  90. X    $tmp = $ARRAY[$#ARRAY\-\|\-];
  91. X
  92. X.fi
  93. XIf there are no elements in the array, returns the undefined value.
  94. X.Ip "print(FILEHANDLE LIST)" 8 10
  95. X.Ip "print(LIST)" 8
  96. X.Ip "print FILEHANDLE LIST" 8
  97. X.Ip "print LIST" 8
  98. X.Ip "print" 8
  99. XPrints a string or a comma-separated list of strings.
  100. XReturns non-zero if successful.
  101. XFILEHANDLE may be a scalar variable name, in which case the variable contains
  102. Xthe name of the filehandle, thus introducing one level of indirection.
  103. X(NOTE: If FILEHANDLE is a variable and the next token is a term, it may be
  104. Xmisinterpreted as an operator unless you interpose a + or put parens around
  105. Xthe arguments.)
  106. XIf FILEHANDLE is omitted, prints by default to standard output (or to the
  107. Xlast selected output channel\*(--see select()).
  108. XIf LIST is also omitted, prints $_ to
  109. X.IR STDOUT .
  110. XTo set the default output channel to something other than
  111. X.I STDOUT
  112. Xuse the select operation.
  113. XNote that, because print takes a LIST, anything in the LIST is evaluated
  114. Xin an array context, and any subroutine that you call will have one or more
  115. Xof its expressions evaluated in an array context.
  116. XAlso be careful not to follow the print keyword with a left parenthesis
  117. Xunless you want the corresponding right parenthesis to terminate the
  118. Xarguments to the print\*(--interpose a + or put parens around all the arguments.
  119. X.Ip "printf(FILEHANDLE LIST)" 8 10
  120. X.Ip "printf(LIST)" 8
  121. X.Ip "printf FILEHANDLE LIST" 8
  122. X.Ip "printf LIST" 8
  123. XEquivalent to a \*(L"print FILEHANDLE sprintf(LIST)\*(R".
  124. X.Ip "push(ARRAY,LIST)" 8 7
  125. XTreats ARRAY (@ is optional) as a stack, and pushes the values of LIST
  126. Xonto the end of ARRAY.
  127. XThe length of ARRAY increases by the length of LIST.
  128. XHas the same effect as
  129. X.nf
  130. X
  131. X    for $value (LIST) {
  132. X        $ARRAY[++$#ARRAY] = $value;
  133. X    }
  134. X
  135. X.fi
  136. Xbut is more efficient.
  137. X.Ip "q/STRING/" 8 5
  138. X.Ip "qq/STRING/" 8
  139. X.Ip "qx/STRING/" 8
  140. XThese are not really functions, but simply syntactic sugar to let you
  141. Xavoid putting too many backslashes into quoted strings.
  142. XThe q operator is a generalized single quote, and the qq operator a
  143. Xgeneralized double quote.
  144. XThe qx operator is a generalized backquote.
  145. XAny non-alphanumeric delimiter can be used in place of /, including newline.
  146. XIf the delimiter is an opening bracket or parenthesis, the final delimiter
  147. Xwill be the corresponding closing bracket or parenthesis.
  148. X(Embedded occurrences of the closing bracket need to be backslashed as usual.)
  149. XExamples:
  150. X.nf
  151. X
  152. X.ne 5
  153. X    $foo = q!I said, "You said, \'She said it.\'"!;
  154. X    $bar = q(\'This is it.\');
  155. X    $today = qx{ date };
  156. X    $_ .= qq
  157. X*** The previous line contains the naughty word "$&".\en
  158. X        if /(ibm|apple|awk)/;      # :-)
  159. X
  160. X.fi
  161. X.Ip "rand(EXPR)" 8 8
  162. X.Ip "rand EXPR" 8
  163. X.Ip "rand" 8
  164. XReturns a random fractional number between 0 and the value of EXPR.
  165. X(EXPR should be positive.)
  166. XIf EXPR is omitted, returns a value between 0 and 1.
  167. XSee also srand().
  168. X.Ip "read(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
  169. X.Ip "read(FILEHANDLE,SCALAR,LENGTH)" 8 5
  170. XAttempts to read LENGTH bytes of data into variable SCALAR from the specified
  171. XFILEHANDLE.
  172. XReturns the number of bytes actually read, or undef if there was an error.
  173. XSCALAR will be grown or shrunk to the length actually read.
  174. XAn OFFSET may be specified to place the read data at some other place
  175. Xthan the beginning of the string.
  176. XThis call is actually implemented in terms of stdio's fread call.  To get
  177. Xa true read system call, see sysread.
  178. X.Ip "readdir(DIRHANDLE)" 8 3
  179. X.Ip "readdir DIRHANDLE" 8
  180. XReturns the next directory entry for a directory opened by opendir().
  181. XIf used in an array context, returns all the rest of the entries in the
  182. Xdirectory.
  183. XIf there are no more entries, returns an undefined value in a scalar context
  184. Xor a null list in an array context.
  185. X.Ip "readlink(EXPR)" 8 6
  186. X.Ip "readlink EXPR" 8
  187. XReturns the value of a symbolic link, if symbolic links are implemented.
  188. XIf not, gives a fatal error.
  189. XIf there is some system error, returns the undefined value and sets $! (errno).
  190. XIf EXPR is omitted, uses $_.
  191. X.Ip "recv(SOCKET,SCALAR,LEN,FLAGS)" 8 4
  192. XReceives a message on a socket.
  193. XAttempts to receive LENGTH bytes of data into variable SCALAR from the specified
  194. XSOCKET filehandle.
  195. XReturns the address of the sender, or the undefined value if there's an error.
  196. XSCALAR will be grown or shrunk to the length actually read.
  197. XTakes the same flags as the system call of the same name.
  198. X.Ip "redo LABEL" 8 8
  199. X.Ip "redo" 8
  200. XThe
  201. X.I redo
  202. Xcommand restarts the loop block without evaluating the conditional again.
  203. XThe
  204. X.I continue
  205. Xblock, if any, is not executed.
  206. XIf the LABEL is omitted, the command refers to the innermost enclosing loop.
  207. XThis command is normally used by programs that want to lie to themselves
  208. Xabout what was just input:
  209. X.nf
  210. X
  211. X.ne 16
  212. X    # a simpleminded Pascal comment stripper
  213. X    # (warning: assumes no { or } in strings)
  214. X    line: while (<STDIN>) {
  215. X        while (s|\|({.*}.*\|){.*}|$1 \||) {}
  216. X        s|{.*}| \||;
  217. X        if (s|{.*| \||) {
  218. X            $front = $_;
  219. X            while (<STDIN>) {
  220. X                if (\|/\|}/\|) {    # end of comment?
  221. X                    s|^|$front{|;
  222. X                    redo line;
  223. X                }
  224. X            }
  225. X        }
  226. X        print;
  227. X    }
  228. X
  229. X.fi
  230. X.Ip "rename(OLDNAME,NEWNAME)" 8 2
  231. XChanges the name of a file.
  232. XReturns 1 for success, 0 otherwise.
  233. XWill not work across filesystem boundaries.
  234. X.Ip "require(EXPR)" 8 6
  235. X.Ip "require EXPR" 8
  236. X.Ip "require" 8
  237. XIncludes the library file specified by EXPR, or by $_ if EXPR is not supplied.
  238. XHas semantics similar to the following subroutine:
  239. X.nf
  240. X
  241. X    sub require {
  242. X        local($filename) = @_;
  243. X        return 1 if $INC{$filename};
  244. X        local($realfilename,$result);
  245. X        ITER: {
  246. X        foreach $prefix (@INC) {
  247. X            $realfilename = "$prefix/$filename";
  248. X            if (-f $realfilename) {
  249. X            $result = do $realfilename;
  250. X            last ITER;
  251. X            }
  252. X        }
  253. X        die "Can't find $filename in \e@INC";
  254. X        }
  255. X        die $@ if $@;
  256. X        die "$filename did not return true value" unless $result;
  257. X        $INC{$filename} = $realfilename;
  258. X        $result;
  259. X    }
  260. X
  261. X.fi
  262. XNote that the file will not be included twice under the same specified name.
  263. X.Ip "reset(EXPR)" 8 6
  264. X.Ip "reset EXPR" 8
  265. X.Ip "reset" 8
  266. XGenerally used in a
  267. X.I continue
  268. Xblock at the end of a loop to clear variables and reset ?? searches
  269. Xso that they work again.
  270. XThe expression is interpreted as a list of single characters (hyphens allowed
  271. Xfor ranges).
  272. XAll variables and arrays beginning with one of those letters are reset to
  273. Xtheir pristine state.
  274. XIf the expression is omitted, one-match searches (?pattern?) are reset to
  275. Xmatch again.
  276. XOnly resets variables or searches in the current package.
  277. XAlways returns 1.
  278. XExamples:
  279. X.nf
  280. X
  281. X.ne 3
  282. X    reset \'X\';    \h'|2i'# reset all X variables
  283. X    reset \'a\-z\';\h'|2i'# reset lower case variables
  284. X    reset;    \h'|2i'# just reset ?? searches
  285. X
  286. X.fi
  287. XNote: resetting \*(L"A\-Z\*(R" is not recommended since you'll wipe out your ARGV and ENV
  288. Xarrays.
  289. X.Sp
  290. XThe use of reset on dbm associative arrays does not change the dbm file.
  291. X(It does, however, flush any entries cached by perl, which may be useful if
  292. Xyou are sharing the dbm file.
  293. XThen again, maybe not.)
  294. X.Ip "return LIST" 8 3
  295. XReturns from a subroutine with the value specified.
  296. X(Note that a subroutine can automatically return
  297. Xthe value of the last expression evaluated.
  298. XThat's the preferred method\*(--use of an explicit
  299. X.I return
  300. Xis a bit slower.)
  301. X.Ip "reverse(LIST)" 8 4
  302. X.Ip "reverse LIST" 8
  303. XIn an array context, returns an array value consisting of the elements
  304. Xof LIST in the opposite order.
  305. XIn a scalar context, returns a string value consisting of the bytes of
  306. Xthe first element of LIST in the opposite order.
  307. X.Ip "rewinddir(DIRHANDLE)" 8 5
  308. X.Ip "rewinddir DIRHANDLE" 8
  309. XSets the current position to the beginning of the directory for the readdir() routine on DIRHANDLE.
  310. X.Ip "rindex(STR,SUBSTR,POSITION)" 8 6
  311. X.Ip "rindex(STR,SUBSTR)" 8 4
  312. XWorks just like index except that it
  313. Xreturns the position of the LAST occurrence of SUBSTR in STR.
  314. XIf POSITION is specified, returns the last occurrence at or before that
  315. Xposition.
  316. X.Ip "rmdir(FILENAME)" 8 4
  317. X.Ip "rmdir FILENAME" 8
  318. XDeletes the directory specified by FILENAME if it is empty.
  319. XIf it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
  320. XIf FILENAME is omitted, uses $_.
  321. X.Ip "s/PATTERN/REPLACEMENT/gieo" 8 3
  322. XSearches a string for a pattern, and if found, replaces that pattern with the
  323. Xreplacement text and returns the number of substitutions made.
  324. XOtherwise it returns false (0).
  325. XThe \*(L"g\*(R" is optional, and if present, indicates that all occurrences
  326. Xof the pattern are to be replaced.
  327. XThe \*(L"i\*(R" is also optional, and if present, indicates that matching
  328. Xis to be done in a case-insensitive manner.
  329. XThe \*(L"e\*(R" is likewise optional, and if present, indicates that
  330. Xthe replacement string is to be evaluated as an expression rather than just
  331. Xas a double-quoted string.
  332. XAny non-alphanumeric delimiter may replace the slashes;
  333. Xif single quotes are used, no
  334. Xinterpretation is done on the replacement string (the e modifier overrides
  335. Xthis, however); if backquotes are used, the replacement string is a command
  336. Xto execute whose output will be used as the actual replacement text.
  337. XIf no string is specified via the =~ or !~ operator,
  338. Xthe $_ string is searched and modified.
  339. X(The string specified with =~ must be a scalar variable, an array element,
  340. Xor an assignment to one of those, i.e. an lvalue.)
  341. XIf the pattern contains a $ that looks like a variable rather than an
  342. Xend-of-string test, the variable will be interpolated into the pattern at
  343. Xrun-time.
  344. XIf you only want the pattern compiled once the first time the variable is
  345. Xinterpolated, add an \*(L"o\*(R" at the end.
  346. XIf the PATTERN evaluates to a null string, the most recent successful
  347. Xregular expression is used instead.
  348. XSee also the section on regular expressions.
  349. XExamples:
  350. X.nf
  351. X
  352. X    s/\|\e\|bgreen\e\|b/mauve/g;        # don't change wintergreen
  353. X
  354. X    $path \|=~ \|s|\|/usr/bin|\|/usr/local/bin|;
  355. X
  356. X    s/Login: $foo/Login: $bar/; # run-time pattern
  357. X
  358. X    ($foo = $bar) =~ s/bar/foo/;
  359. X
  360. X    $_ = \'abc123xyz\';
  361. X    s/\ed+/$&*2/e;        # yields \*(L'abc246xyz\*(R'
  362. X    s/\ed+/sprintf("%5d",$&)/e;    # yields \*(L'abc  246xyz\*(R'
  363. X    s/\ew/$& x 2/eg;        # yields \*(L'aabbcc  224466xxyyzz\*(R'
  364. X
  365. X    s/\|([^ \|]*\|) *\|([^ \|]*\|)\|/\|$2 $1/;    # reverse 1st two fields
  366. X
  367. X.fi
  368. X(Note the use of $ instead of \|\e\| in the last example.  See section
  369. Xon regular expressions.)
  370. X.Ip "scalar(EXPR)" 8 3
  371. XForces EXPR to be interpreted in a scalar context and returns the value
  372. Xof EXPR.
  373. X.Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
  374. XRandomly positions the file pointer for FILEHANDLE, just like the fseek()
  375. Xcall of stdio.
  376. XFILEHANDLE may be an expression whose value gives the name of the filehandle.
  377. XReturns 1 upon success, 0 otherwise.
  378. X.Ip "seekdir(DIRHANDLE,POS)" 8 3
  379. XSets the current position for the readdir() routine on DIRHANDLE.
  380. XPOS must be a value returned by telldir().
  381. XHas the same caveats about possible directory compaction as the corresponding
  382. Xsystem library routine.
  383. X.Ip "select(FILEHANDLE)" 8 3
  384. X.Ip "select" 8 3
  385. XReturns the currently selected filehandle.
  386. XSets the current default filehandle for output, if FILEHANDLE is supplied.
  387. XThis has two effects: first, a
  388. X.I write
  389. Xor a
  390. X.I print
  391. Xwithout a filehandle will default to this FILEHANDLE.
  392. XSecond, references to variables related to output will refer to this output
  393. Xchannel.
  394. XFor example, if you have to set the top of form format for more than
  395. Xone output channel, you might do the following:
  396. X.nf
  397. X
  398. X.ne 4
  399. X    select(REPORT1);
  400. X    $^ = \'report1_top\';
  401. X    select(REPORT2);
  402. X    $^ = \'report2_top\';
  403. X
  404. X.fi
  405. XFILEHANDLE may be an expression whose value gives the name of the actual filehandle.
  406. XThus:
  407. X.nf
  408. X
  409. X    $oldfh = select(STDERR); $| = 1; select($oldfh);
  410. X
  411. X.fi
  412. X.Ip "select(RBITS,WBITS,EBITS,TIMEOUT)" 8 3
  413. XThis calls the select system call with the bitmasks specified, which can
  414. Xbe constructed using fileno() and vec(), along these lines:
  415. X.nf
  416. X
  417. X    $rin = $win = $ein = '';
  418. X    vec($rin,fileno(STDIN),1) = 1;
  419. X    vec($win,fileno(STDOUT),1) = 1;
  420. X    $ein = $rin | $win;
  421. X
  422. X.fi
  423. XIf you want to select on many filehandles you might wish to write a subroutine:
  424. X.nf
  425. X
  426. X    sub fhbits {
  427. X        local(@fhlist) = split(' ',$_[0]);
  428. X        local($bits);
  429. X        for (@fhlist) {
  430. X        vec($bits,fileno($_),1) = 1;
  431. X        }
  432. X        $bits;
  433. X    }
  434. X    $rin = &fhbits('STDIN TTY SOCK');
  435. X
  436. X.fi
  437. XThe usual idiom is:
  438. X.nf
  439. X
  440. X    ($nfound,$timeleft) =
  441. X      select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  442. X
  443. Xor to block until something becomes ready:
  444. X
  445. X.ie t \{\
  446. X    $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
  447. X'br\}
  448. X.el \{\
  449. X    $nfound = select($rout=$rin, $wout=$win,
  450. X                $eout=$ein, undef);
  451. X'br\}
  452. X
  453. X.fi
  454. XAny of the bitmasks can also be undef.
  455. XThe timeout, if specified, is in seconds, which may be fractional.
  456. XNOTE: not all implementations are capable of returning the $timeleft.
  457. XIf not, they always return $timeleft equal to the supplied $timeout.
  458. X.Ip "semctl(ID,SEMNUM,CMD,ARG)" 8 4
  459. XCalls the System V IPC function semctl.  If CMD is &IPC_STAT or
  460. X&GETALL, then ARG must be a variable which will hold the returned
  461. Xsemid_ds structure or semaphore value array.  Returns like ioctl: the
  462. Xundefined value for error, "0 but true" for zero, or the actual return
  463. Xvalue otherwise.
  464. X.Ip "semget(KEY,NSEMS,SIZE,FLAGS)" 8 4
  465. XCalls the System V IPC function semget.  Returns the semaphore id, or
  466. Xthe undefined value if there is an error.
  467. X.Ip "semop(KEY,OPSTRING)" 8 4
  468. XCalls the System V IPC function semop to perform semaphore operations
  469. Xsuch as signaling and waiting.  OPSTRING must be a packed array of
  470. Xsemop structures.  Each semop structure can be generated with
  471. X\&'pack("sss", $semnum, $semop, $semflag)'.  The number of semaphore
  472. Xoperations is implied by the length of OPSTRING.  Returns true if
  473. Xsuccessful, or false if there is an error.  As an example, the
  474. Xfollowing code waits on semaphore $semnum of semaphore id $semid:
  475. X.nf
  476. X
  477. X    $semop = pack("sss", $semnum, -1, 0);
  478. X    die "Semaphore trouble: $!\en" unless semop($semid, $semop);
  479. X
  480. X.fi
  481. XTo signal the semaphore, replace "-1" with "1".
  482. X.Ip "send(SOCKET,MSG,FLAGS,TO)" 8 4
  483. X.Ip "send(SOCKET,MSG,FLAGS)" 8
  484. XSends a message on a socket.
  485. XTakes the same flags as the system call of the same name.
  486. XOn unconnected sockets you must specify a destination to send TO.
  487. XReturns the number of characters sent, or the undefined value if
  488. Xthere is an error.
  489. X.Ip "setpgrp(PID,PGRP)" 8 4
  490. XSets the current process group for the specified PID, 0 for the current
  491. Xprocess.
  492. XWill produce a fatal error if used on a machine that doesn't implement
  493. Xsetpgrp(2).
  494. X.Ip "setpriority(WHICH,WHO,PRIORITY)" 8 4
  495. XSets the current priority for a process, a process group, or a user.
  496. X(See setpriority(2).)
  497. XWill produce a fatal error if used on a machine that doesn't implement
  498. Xsetpriority(2).
  499. X.Ip "setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)" 8 3
  500. XSets the socket option requested.
  501. XReturns undefined if there is an error.
  502. XOPTVAL may be specified as undef if you don't want to pass an argument.
  503. X.Ip "shift(ARRAY)" 8 6
  504. X.Ip "shift ARRAY" 8
  505. X.Ip "shift" 8
  506. XShifts the first value of the array off and returns it,
  507. Xshortening the array by 1 and moving everything down.
  508. XIf there are no elements in the array, returns the undefined value.
  509. XIf ARRAY is omitted, shifts the @ARGV array in the main program, and the @_
  510. Xarray in subroutines.
  511. X(This is determined lexically.)
  512. XSee also unshift(), push() and pop().
  513. XShift() and unshift() do the same thing to the left end of an array that push()
  514. Xand pop() do to the right end.
  515. X.Ip "shmctl(ID,CMD,ARG)" 8 4
  516. XCalls the System V IPC function shmctl.  If CMD is &IPC_STAT, then ARG
  517. Xmust be a variable which will hold the returned shmid_ds structure.
  518. XReturns like ioctl: the undefined value for error, "0 but true" for
  519. Xzero, or the actual return value otherwise.
  520. X.Ip "shmget(KEY,SIZE,FLAGS)" 8 4
  521. XCalls the System V IPC function shmget.  Returns the shared memory
  522. Xsegment id, or the undefined value if there is an error.
  523. X.Ip "shmread(ID,VAR,POS,SIZE)" 8 4
  524. X.Ip "shmwrite(ID,STRING,POS,SIZE)" 8
  525. XReads or writes the System V shared memory segment ID starting at
  526. Xposition POS for size SIZE by attaching to it, copying in/out, and
  527. Xdetaching from it.  When reading, VAR must be a variable which
  528. Xwill hold the data read.  When writing, if STRING is too long,
  529. Xonly SIZE bytes are used; if STRING is too short, nulls are
  530. Xwritten to fill out SIZE bytes.  Return true if successful, or
  531. Xfalse if there is an error.
  532. X.Ip "shutdown(SOCKET,HOW)" 8 3
  533. XShuts down a socket connection in the manner indicated by HOW, which has
  534. Xthe same interpretation as in the system call of the same name.
  535. X.Ip "sin(EXPR)" 8 4
  536. X.Ip "sin EXPR" 8
  537. XReturns the sine of EXPR (expressed in radians).
  538. XIf EXPR is omitted, returns sine of $_.
  539. X.Ip "sleep(EXPR)" 8 6
  540. X.Ip "sleep EXPR" 8
  541. X.Ip "sleep" 8
  542. XCauses the script to sleep for EXPR seconds, or forever if no EXPR.
  543. XMay be interrupted by sending the process a SIGALARM.
  544. XReturns the number of seconds actually slept.
  545. X.Ip "socket(SOCKET,DOMAIN,TYPE,PROTOCOL)" 8 3
  546. XOpens a socket of the specified kind and attaches it to filehandle SOCKET.
  547. XDOMAIN, TYPE and PROTOCOL are specified the same as for the system call
  548. Xof the same name.
  549. XYou may need to run h2ph on sys/socket.h to get the proper values handy
  550. Xin a perl library file.
  551. XReturn true if successful.
  552. XSee the example in the section on Interprocess Communication.
  553. X.Ip "socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)" 8 3
  554. XCreates an unnamed pair of sockets in the specified domain, of the specified
  555. Xtype.
  556. XDOMAIN, TYPE and PROTOCOL are specified the same as for the system call
  557. Xof the same name.
  558. XIf unimplemented, yields a fatal error.
  559. XReturn true if successful.
  560. X.Ip "sort(SUBROUTINE LIST)" 8 9
  561. X.Ip "sort(LIST)" 8
  562. X.Ip "sort SUBROUTINE LIST" 8
  563. X.Ip "sort LIST" 8
  564. XSorts the LIST and returns the sorted array value.
  565. XNonexistent values of arrays are stripped out.
  566. XIf SUBROUTINE is omitted, sorts in standard string comparison order.
  567. XIf SUBROUTINE is specified, gives the name of a subroutine that returns
  568. Xan integer less than, equal to, or greater than 0,
  569. Xdepending on how the elements of the array are to be ordered.
  570. XIn the interests of efficiency the normal calling code for subroutines
  571. Xis bypassed, with the following effects: the subroutine may not be a recursive
  572. Xsubroutine, and the two elements to be compared are passed into the subroutine
  573. Xnot via @_ but as $a and $b (see example below).
  574. XThey are passed by reference so don't modify $a and $b.
  575. XSUBROUTINE may be a scalar variable name, in which case the value provides
  576. Xthe name of the subroutine to use.
  577. XExamples:
  578. X.nf
  579. X
  580. X.ne 4
  581. X    sub byage {
  582. X        $age{$a} - $age{$b};    # presuming integers
  583. X    }
  584. X    @sortedclass = sort byage @class;
  585. X
  586. X.ne 9
  587. X    sub reverse { $a lt $b ? 1 : $a gt $b ? \-1 : 0; }
  588. X    @harry = (\'dog\',\'cat\',\'x\',\'Cain\',\'Abel\');
  589. X    @george = (\'gone\',\'chased\',\'yz\',\'Punished\',\'Axed\');
  590. X    print sort @harry;
  591. X        # prints AbelCaincatdogx
  592. X    print sort reverse @harry;
  593. X        # prints xdogcatCainAbel
  594. X    print sort @george, \'to\', @harry;
  595. X        # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  596. X
  597. X.fi
  598. X.Ip "splice(ARRAY,OFFSET,LENGTH,LIST)" 8 8
  599. X.Ip "splice(ARRAY,OFFSET,LENGTH)" 8
  600. X.Ip "splice(ARRAY,OFFSET)" 8
  601. XRemoves the elements designated by OFFSET and LENGTH from an array, and
  602. Xreplaces them with the elements of LIST, if any.
  603. XReturns the elements removed from the array.
  604. XThe array grows or shrinks as necessary.
  605. XIf LENGTH is omitted, removes everything from OFFSET onward.
  606. XThe following equivalencies hold (assuming $[ == 0):
  607. X.nf
  608. X
  609. X    push(@a,$x,$y)\h'|3.5i'splice(@a,$#a+1,0,$x,$y)
  610. X    pop(@a)\h'|3.5i'splice(@a,-1)
  611. X    shift(@a)\h'|3.5i'splice(@a,0,1)
  612. X    unshift(@a,$x,$y)\h'|3.5i'splice(@a,0,0,$x,$y)
  613. X    $a[$x] = $y\h'|3.5i'splice(@a,$x,1,$y);
  614. X
  615. XExample, assuming array lengths are passed before arrays:
  616. X    
  617. X    sub aeq {    # compare two array values
  618. X        local(@a) = splice(@_,0,shift);
  619. X        local(@b) = splice(@_,0,shift);
  620. X        return 0 unless @a == @b;    # same len?
  621. X        while (@a) {
  622. X            return 0 if pop(@a) ne pop(@b);
  623. X        }
  624. X        return 1;
  625. X    }
  626. X    if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  627. X
  628. X.fi
  629. X.Ip "split(/PATTERN/,EXPR,LIMIT)" 8 8
  630. X.Ip "split(/PATTERN/,EXPR)" 8 8
  631. X.Ip "split(/PATTERN/)" 8
  632. X.Ip "split" 8
  633. XSplits a string into an array of strings, and returns it.
  634. X(If not in an array context, returns the number of fields found and splits
  635. Xinto the @_ array.
  636. X(In an array context, you can force the split into @_
  637. Xby using ?? as the pattern delimiters, but it still returns the array value.))
  638. XIf EXPR is omitted, splits the $_ string.
  639. XIf PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
  640. XAnything matching PATTERN is taken to be a delimiter separating the fields.
  641. X(Note that the delimiter may be longer than one character.)
  642. XIf LIMIT is specified, splits into no more than that many fields (though it
  643. Xmay split into fewer).
  644. XIf LIMIT is unspecified, trailing null fields are stripped (which
  645. Xpotential users of pop() would do well to remember).
  646. XA pattern matching the null string (not to be confused with a null pattern //,
  647. Xwhich is just one member of the set of patterns matching a null string)
  648. Xwill split the value of EXPR into separate characters at each point it
  649. Xmatches that way.
  650. XFor example:
  651. X.nf
  652. X
  653. X    print join(\':\', split(/ */, \'hi there\'));
  654. X
  655. X.fi
  656. Xproduces the output \*(L'h:i:t:h:e:r:e\*(R'.
  657. X.Sp
  658. XThe LIMIT parameter can be used to partially split a line
  659. X.nf
  660. X
  661. X    ($login, $passwd, $remainder) = split(\|/\|:\|/\|, $_, 3);
  662. X
  663. X.fi
  664. X(When assigning to a list, if LIMIT is omitted, perl supplies a LIMIT one
  665. Xlarger than the number of variables in the list, to avoid unnecessary work.
  666. XFor the list above LIMIT would have been 4 by default.
  667. XIn time critical applications it behooves you not to split into
  668. Xmore fields than you really need.)
  669. X.Sp
  670. XIf the PATTERN contains parentheses, additional array elements are created
  671. Xfrom each matching substring in the delimiter.
  672. X.Sp
  673. X    split(/([,-])/,"1-10,20");
  674. X.Sp
  675. Xproduces the array value
  676. X.Sp
  677. X    (1,'-',10,',',20)
  678. X.Sp
  679. XThe pattern /PATTERN/ may be replaced with an expression to specify patterns
  680. Xthat vary at runtime.
  681. X(To do runtime compilation only once, use /$variable/o.)
  682. XAs a special case, specifying a space (\'\ \') will split on white space
  683. Xjust as split with no arguments does, but leading white space does NOT
  684. Xproduce a null first field.
  685. XThus, split(\'\ \') can be used to emulate
  686. X.IR awk 's
  687. Xdefault behavior, whereas
  688. Xsplit(/\ /) will give you as many null initial fields as there are
  689. Xleading spaces.
  690. X.Sp
  691. XExample:
  692. X.nf
  693. X
  694. X.ne 5
  695. X    open(passwd, \'/etc/passwd\');
  696. X    while (<passwd>) {
  697. X.ie t \{\
  698. X        ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(\|/\|:\|/\|);
  699. X'br\}
  700. X.el \{\
  701. X        ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  702. X            = split(\|/\|:\|/\|);
  703. X'br\}
  704. X        .\|.\|.
  705. X    }
  706. X
  707. X.fi
  708. X(Note that $shell above will still have a newline on it.  See chop().)
  709. XSee also
  710. X.IR join .
  711. X.Ip "sprintf(FORMAT,LIST)" 8 4
  712. XReturns a string formatted by the usual printf conventions.
  713. XThe * character is not supported.
  714. X.Ip "sqrt(EXPR)" 8 4
  715. X.Ip "sqrt EXPR" 8
  716. XReturn the square root of EXPR.
  717. XIf EXPR is omitted, returns square root of $_.
  718. X.Ip "srand(EXPR)" 8 4
  719. X.Ip "srand EXPR" 8
  720. XSets the random number seed for the
  721. X.I rand
  722. Xoperator.
  723. XIf EXPR is omitted, does srand(time).
  724. X.Ip "stat(FILEHANDLE)" 8 8
  725. X.Ip "stat FILEHANDLE" 8
  726. X.Ip "stat(EXPR)" 8
  727. X.Ip "stat SCALARVARIABLE" 8
  728. XReturns a 13-element array giving the statistics for a file, either the file
  729. Xopened via FILEHANDLE, or named by EXPR.
  730. XTypically used as follows:
  731. X.nf
  732. X
  733. X.ne 3
  734. X    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  735. X       $atime,$mtime,$ctime,$blksize,$blocks)
  736. X           = stat($filename);
  737. X
  738. X.fi
  739. XIf stat is passed the special filehandle consisting of an underline,
  740. Xno stat is done, but the current contents of the stat structure from
  741. Xthe last stat or filetest are returned.
  742. XExample:
  743. X.nf
  744. X
  745. X.ne 3
  746. X    if (-x $file && (($d) = stat(_)) && $d < 0) {
  747. X        print "$file is executable NFS file\en";
  748. X    }
  749. X
  750. X.fi
  751. X.Ip "study(SCALAR)" 8 6
  752. X.Ip "study SCALAR" 8
  753. X.Ip "study"
  754. XTakes extra time to study SCALAR ($_ if unspecified) in anticipation of
  755. Xdoing many pattern matches on the string before it is next modified.
  756. XThis may or may not save time, depending on the nature and number of patterns
  757. Xyou are searching on, and on the distribution of character frequencies in
  758. Xthe string to be searched\*(--you probably want to compare runtimes with and
  759. Xwithout it to see which runs faster.
  760. XThose loops which scan for many short constant strings (including the constant
  761. Xparts of more complex patterns) will benefit most.
  762. XYou may have only one study active at a time\*(--if you study a different
  763. Xscalar the first is \*(L"unstudied\*(R".
  764. X(The way study works is this: a linked list of every character in the string
  765. Xto be searched is made, so we know, for example, where all the \*(L'k\*(R' characters
  766. Xare.
  767. XFrom each search string, the rarest character is selected, based on some
  768. Xstatic frequency tables constructed from some C programs and English text.
  769. XOnly those places that contain this \*(L"rarest\*(R" character are examined.)
  770. X.Sp
  771. XFor example, here is a loop which inserts index producing entries before any line
  772. Xcontaining a certain pattern:
  773. X.nf
  774. X
  775. X.ne 8
  776. X    while (<>) {
  777. X        study;
  778. X        print ".IX foo\en" if /\ebfoo\eb/;
  779. X        print ".IX bar\en" if /\ebbar\eb/;
  780. X        print ".IX blurfl\en" if /\ebblurfl\eb/;
  781. X        .\|.\|.
  782. X        print;
  783. X    }
  784. X
  785. X.fi
  786. XIn searching for /\ebfoo\eb/, only those locations in $_ that contain \*(L'f\*(R'
  787. Xwill be looked at, because \*(L'f\*(R' is rarer than \*(L'o\*(R'.
  788. XIn general, this is a big win except in pathological cases.
  789. XThe only question is whether it saves you more time than it took to build
  790. Xthe linked list in the first place.
  791. X.Sp
  792. XNote that if you have to look for strings that you don't know till runtime,
  793. Xyou can build an entire loop as a string and eval that to avoid recompiling
  794. Xall your patterns all the time.
  795. XTogether with undefining $/ to input entire files as one record, this can
  796. Xbe very fast, often faster than specialized programs like fgrep.
  797. XThe following scans a list of files (@files)
  798. Xfor a list of words (@words), and prints out the names of those files that
  799. Xcontain a match:
  800. X.nf
  801. X
  802. X.ne 12
  803. X    $search = \'while (<>) { study;\';
  804. X    foreach $word (@words) {
  805. X        $search .= "++\e$seen{\e$ARGV} if /\eb$word\eb/;\en";
  806. X    }
  807. X    $search .= "}";
  808. X    @ARGV = @files;
  809. X    undef $/;
  810. X    eval $search;        # this screams
  811. X    $/ = "\en";        # put back to normal input delim
  812. X    foreach $file (sort keys(%seen)) {
  813. X        print $file, "\en";
  814. X    }
  815. X
  816. X.fi
  817. X.Ip "substr(EXPR,OFFSET,LEN)" 8 2
  818. X.Ip "substr(EXPR,OFFSET)" 8 2
  819. XExtracts a substring out of EXPR and returns it.
  820. XFirst character is at offset 0, or whatever you've set $[ to.
  821. XIf OFFSET is negative, starts that far from the end of the string.
  822. XIf LEN is omitted, returns everything to the end of the string.
  823. XYou can use the substr() function as an lvalue, in which case EXPR must
  824. Xbe an lvalue.
  825. XIf you assign something shorter than LEN, the string will shrink, and
  826. Xif you assign something longer than LEN, the string will grow to accommodate it.
  827. XTo keep the string the same length you may need to pad or chop your value using
  828. Xsprintf().
  829. X.Ip "symlink(OLDFILE,NEWFILE)" 8 2
  830. XCreates a new filename symbolically linked to the old filename.
  831. XReturns 1 for success, 0 otherwise.
  832. XOn systems that don't support symbolic links, produces a fatal error at
  833. Xrun time.
  834. XTo check for that, use eval:
  835. X.nf
  836. X
  837. X    $symlink_exists = (eval \'symlink("","");\', $@ eq \'\');
  838. X
  839. X.fi
  840. X.Ip "syscall(LIST)" 8 6
  841. X.Ip "syscall LIST" 8
  842. XCalls the system call specified as the first element of the list, passing
  843. Xthe remaining elements as arguments to the system call.
  844. XIf unimplemented, produces a fatal error.
  845. XThe arguments are interpreted as follows: if a given argument is numeric,
  846. Xthe argument is passed as an int.
  847. XIf not, the pointer to the string value is passed.
  848. XYou are responsible to make sure a string is pre-extended long enough
  849. Xto receive any result that might be written into a string.
  850. XIf your integer arguments are not literals and have never been interpreted
  851. Xin a numeric context, you may need to add 0 to them to force them to look
  852. Xlike numbers.
  853. X.nf
  854. X
  855. X    require 'syscall.ph';        # may need to run h2ph
  856. X    syscall(&SYS_write, fileno(STDOUT), "hi there\en", 9);
  857. X
  858. X.fi
  859. X.Ip "sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
  860. X.Ip "sysread(FILEHANDLE,SCALAR,LENGTH)" 8 5
  861. XAttempts to read LENGTH bytes of data into variable SCALAR from the specified
  862. XFILEHANDLE, using the system call read(2).
  863. XIt bypasses stdio, so mixing this with other kinds of reads may cause
  864. Xconfusion.
  865. XReturns the number of bytes actually read, or undef if there was an error.
  866. XSCALAR will be grown or shrunk to the length actually read.
  867. XAn OFFSET may be specified to place the read data at some other place
  868. Xthan the beginning of the string.
  869. X.Ip "system(LIST)" 8 6
  870. X.Ip "system LIST" 8
  871. XDoes exactly the same thing as \*(L"exec LIST\*(R" except that a fork
  872. Xis done first, and the parent process waits for the child process to complete.
  873. XNote that argument processing varies depending on the number of arguments.
  874. XThe return value is the exit status of the program as returned by the wait()
  875. Xcall.
  876. XTo get the actual exit value divide by 256.
  877. XSee also
  878. X.IR exec .
  879. X.Ip "syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
  880. X.Ip "syswrite(FILEHANDLE,SCALAR,LENGTH)" 8 5
  881. XAttempts to write LENGTH bytes of data from variable SCALAR to the specified
  882. XFILEHANDLE, using the system call write(2).
  883. XIt bypasses stdio, so mixing this with prints may cause
  884. Xconfusion.
  885. XReturns the number of bytes actually written, or undef if there was an error.
  886. XAn OFFSET may be specified to place the read data at some other place
  887. Xthan the beginning of the string.
  888. X.Ip "tell(FILEHANDLE)" 8 6
  889. X.Ip "tell FILEHANDLE" 8 6
  890. X.Ip "tell" 8
  891. XReturns the current file position for FILEHANDLE.
  892. XFILEHANDLE may be an expression whose value gives the name of the actual
  893. Xfilehandle.
  894. XIf FILEHANDLE is omitted, assumes the file last read.
  895. X.Ip "telldir(DIRHANDLE)" 8 5
  896. X.Ip "telldir DIRHANDLE" 8
  897. XReturns the current position of the readdir() routines on DIRHANDLE.
  898. XValue may be given to seekdir() to access a particular location in
  899. Xa directory.
  900. XHas the same caveats about possible directory compaction as the corresponding
  901. Xsystem library routine.
  902. X.Ip "time" 8 4
  903. XReturns the number of non-leap seconds since 00:00:00 UTC, January 1, 1970.
  904. XSuitable for feeding to gmtime() and localtime().
  905. X.Ip "times" 8 4
  906. XReturns a four-element array giving the user and system times, in seconds, for this
  907. Xprocess and the children of this process.
  908. X.Sp
  909. X    ($user,$system,$cuser,$csystem) = times;
  910. X.Sp
  911. X.Ip "tr/SEARCHLIST/REPLACEMENTLIST/cds" 8 5
  912. X.Ip "y/SEARCHLIST/REPLACEMENTLIST/cds" 8
  913. XTranslates all occurrences of the characters found in the search list with
  914. Xthe corresponding character in the replacement list.
  915. XIt returns the number of characters replaced or deleted.
  916. XIf no string is specified via the =~ or !~ operator,
  917. Xthe $_ string is translated.
  918. X(The string specified with =~ must be a scalar variable, an array element,
  919. Xor an assignment to one of those, i.e. an lvalue.)
  920. XFor
  921. X.I sed
  922. Xdevotees,
  923. X.I y
  924. Xis provided as a synonym for
  925. X.IR tr .
  926. X.Sp
  927. XIf the c modifier is specified, the SEARCHLIST character set is complemented.
  928. XIf the d modifier is specified, any characters specified by SEARCHLIST that
  929. Xare not found in REPLACEMENTLIST are deleted.
  930. X(Note that this is slightly more flexible than the behavior of some
  931. X.I tr
  932. Xprograms, which delete anything they find in the SEARCHLIST, period.)
  933. XIf the s modifier is specified, sequences of characters that were translated
  934. Xto the same character are squashed down to 1 instance of the character.
  935. X.Sp
  936. XIf the d modifier was used, the REPLACEMENTLIST is always interpreted exactly
  937. Xas specified.
  938. XOtherwise, if the REPLACEMENTLIST is shorter than the SEARCHLIST,
  939. Xthe final character is replicated till it is long enough.
  940. XIf the REPLACEMENTLIST is null, the SEARCHLIST is replicated.
  941. XThis latter is useful for counting characters in a class, or for squashing
  942. Xcharacter sequences in a class.
  943. X.Sp
  944. XExamples:
  945. X.nf
  946. X
  947. X    $ARGV[1] \|=~ \|y/A\-Z/a\-z/;    \h'|3i'# canonicalize to lower case
  948. X
  949. X    $cnt = tr/*/*/;        \h'|3i'# count the stars in $_
  950. X
  951. X    $cnt = tr/0\-9//;        \h'|3i'# count the digits in $_
  952. X
  953. X    tr/a\-zA\-Z//s;    \h'|3i'# bookkeeper \-> bokeper
  954. X
  955. X    ($HOST = $host) =~ tr/a\-z/A\-Z/;
  956. X
  957. X    y/a\-zA\-Z/ /cs;    \h'|3i'# change non-alphas to single space
  958. X
  959. X    tr/\e200\-\e377/\e0\-\e177/;\h'|3i'# delete 8th bit
  960. X
  961. X.fi
  962. X.Ip "truncate(FILEHANDLE,LENGTH)" 8 4
  963. X.Ip "truncate(EXPR,LENGTH)" 8
  964. XTruncates the file opened on FILEHANDLE, or named by EXPR, to the specified
  965. Xlength.
  966. XProduces a fatal error if truncate isn't implemented on your system.
  967. X.Ip "umask(EXPR)" 8 4
  968. X.Ip "umask EXPR" 8
  969. X.Ip "umask" 8
  970. XSets the umask for the process and returns the old one.
  971. XIf EXPR is omitted, merely returns current umask.
  972. X.Ip "undef(EXPR)" 8 6
  973. X.Ip "undef EXPR" 8
  974. X.Ip "undef" 8
  975. XUndefines the value of EXPR, which must be an lvalue.
  976. XUse only on a scalar value, an entire array, or a subroutine name (using &).
  977. X(Undef will probably not do what you expect on most predefined variables or
  978. Xdbm array values.)
  979. XAlways returns the undefined value.
  980. XYou can omit the EXPR, in which case nothing is undefined, but you still
  981. Xget an undefined value that you could, for instance, return from a subroutine.
  982. XExamples:
  983. X.nf
  984. X
  985. X.ne 6
  986. X    undef $foo;
  987. X    undef $bar{'blurfl'};
  988. X    undef @ary;
  989. X    undef %assoc;
  990. X    undef &mysub;
  991. X    return (wantarray ? () : undef) if $they_blew_it;
  992. X
  993. X.fi
  994. X.Ip "unlink(LIST)" 8 4
  995. X.Ip "unlink LIST" 8
  996. XDeletes a list of files.
  997. XReturns the number of files successfully deleted.
  998. X.nf
  999. X
  1000. X.ne 2
  1001. X    $cnt = unlink \'a\', \'b\', \'c\';
  1002. X    unlink @goners;
  1003. X    unlink <*.bak>;
  1004. X
  1005. X.fi
  1006. XNote: unlink will not delete directories unless you are superuser and the
  1007. X.B \-U
  1008. Xflag is supplied to
  1009. X.IR perl .
  1010. XEven if these conditions are met, be warned that unlinking a directory
  1011. Xcan inflict damage on your filesystem.
  1012. XUse rmdir instead.
  1013. X.Ip "unpack(TEMPLATE,EXPR)" 8 4
  1014. XUnpack does the reverse of pack: it takes a string representing
  1015. Xa structure and expands it out into an array value, returning the array
  1016. Xvalue.
  1017. X(In a scalar context, it merely returns the first value produced.)
  1018. XThe TEMPLATE has the same format as in the pack function.
  1019. XHere's a subroutine that does substring:
  1020. X.nf
  1021. X
  1022. X.ne 4
  1023. X    sub substr {
  1024. X        local($what,$where,$howmuch) = @_;
  1025. X        unpack("x$where a$howmuch", $what);
  1026. X    }
  1027. X
  1028. X.ne 3
  1029. Xand then there's
  1030. X
  1031. X    sub ord { unpack("c",$_[0]); }
  1032. X
  1033. X.fi
  1034. XIn addition, you may prefix a field with a %<number> to indicate that
  1035. Xyou want a <number>-bit checksum of the items instead of the items themselves.
  1036. XDefault is a 16-bit checksum.
  1037. XFor example, the following computes the same number as the System V sum program:
  1038. X.nf
  1039. X
  1040. X.ne 4
  1041. X    while (<>) {
  1042. X        $checksum += unpack("%16C*", $_);
  1043. X    }
  1044. X    $checksum %= 65536;
  1045. X
  1046. X.fi
  1047. X.Ip "unshift(ARRAY,LIST)" 8 4
  1048. XDoes the opposite of a
  1049. X.IR shift .
  1050. XOr the opposite of a
  1051. X.IR push ,
  1052. Xdepending on how you look at it.
  1053. XPrepends list to the front of the array, and returns the number of elements
  1054. Xin the new array.
  1055. X.nf
  1056. X
  1057. X    unshift(ARGV, \'\-e\') unless $ARGV[0] =~ /^\-/;
  1058. X
  1059. X.fi
  1060. X.Ip "utime(LIST)" 8 2
  1061. X.Ip "utime LIST" 8 2
  1062. XChanges the access and modification times on each file of a list of files.
  1063. XThe first two elements of the list must be the NUMERICAL access and
  1064. Xmodification times, in that order.
  1065. XReturns the number of files successfully changed.
  1066. XThe inode modification time of each file is set to the current time.
  1067. XExample of a \*(L"touch\*(R" command:
  1068. X.nf
  1069. X
  1070. X.ne 3
  1071. X    #!/usr/bin/perl
  1072. X    $now = time;
  1073. X    utime $now, $now, @ARGV;
  1074. X
  1075. X.fi
  1076. X.Ip "values(ASSOC_ARRAY)" 8 6
  1077. X.Ip "values ASSOC_ARRAY" 8
  1078. XReturns a normal array consisting of all the values of the named associative
  1079. Xarray.
  1080. XThe values are returned in an apparently random order, but it is the same order
  1081. Xas either the keys() or each() function would produce on the same array.
  1082. XSee also keys() and each().
  1083. X.Ip "vec(EXPR,OFFSET,BITS)" 8 2
  1084. XTreats a string as a vector of unsigned integers, and returns the value
  1085. Xof the bitfield specified.
  1086. XMay also be assigned to.
  1087. XBITS must be a power of two from 1 to 32.
  1088. X.Sp
  1089. XVectors created with vec() can also be manipulated with the logical operators
  1090. X|, & and ^,
  1091. Xwhich will assume a bit vector operation is desired when both operands are
  1092. Xstrings.
  1093. XThis interpretation is not enabled unless there is at least one vec() in
  1094. Xyour program, to protect older programs.
  1095. X.Sp
  1096. XTo transform a bit vector into a string or array of 0's and 1's, use these:
  1097. X.nf
  1098. X
  1099. X    $bits = unpack("b*", $vector);
  1100. X    @bits = split(//, unpack("b*", $vector));
  1101. X
  1102. X.fi
  1103. XIf you know the exact length in bits, it can be used in place of the *.
  1104. X.Ip "wait" 8 6
  1105. XWaits for a child process to terminate and returns the pid of the deceased
  1106. Xprocess, or -1 if there are no child processes.
  1107. XThe status is returned in $?.
  1108. X.Ip "waitpid(PID,FLAGS)" 8 6
  1109. XWaits for a particular child process to terminate and returns the pid of the deceased
  1110. Xprocess, or -1 if there is no such child process.
  1111. XThe status is returned in $?.
  1112. XIf you say
  1113. X.nf
  1114. X
  1115. X    require "sys/wait.h";
  1116. X    .\|.\|.
  1117. X    waitpid(-1,&WNOHANG);
  1118. X
  1119. X.fi
  1120. Xthen you can do a non-blocking wait for any process.  Non-blocking wait
  1121. Xis only available on machines supporting either the
  1122. X.I waitpid (2)
  1123. Xor
  1124. X.I wait4 (2)
  1125. Xsystem calls.
  1126. XHowever, waiting for a particular pid with FLAGS of 0 is implemented
  1127. Xeverywhere.  (Perl emulates the system call by remembering the status
  1128. Xvalues of processes that have exited but have not been harvested by the
  1129. XPerl script yet.)
  1130. X.Ip "wantarray" 8 4
  1131. XReturns true if the context of the currently executing subroutine
  1132. Xis looking for an array value.
  1133. XReturns false if the context is looking for a scalar.
  1134. X.nf
  1135. X
  1136. X    return wantarray ? () : undef;
  1137. X
  1138. X.fi
  1139. X.Ip "warn(LIST)" 8 4
  1140. X.Ip "warn LIST" 8
  1141. XProduces a message on STDERR just like \*(L"die\*(R", but doesn't exit.
  1142. X.Ip "write(FILEHANDLE)" 8 6
  1143. X.Ip "write(EXPR)" 8
  1144. X.Ip "write" 8
  1145. XWrites a formatted record (possibly multi-line) to the specified file,
  1146. Xusing the format associated with that file.
  1147. XBy default the format for a file is the one having the same name is the
  1148. Xfilehandle, but the format for the current output channel (see
  1149. X.IR select )
  1150. Xmay be set explicitly
  1151. Xby assigning the name of the format to the $~ variable.
  1152. X.Sp
  1153. XTop of form processing is handled automatically:
  1154. Xif there is insufficient room on the current page for the formatted 
  1155. Xrecord, the page is advanced by writing a form feed,
  1156. Xa special top-of-page format is used
  1157. Xto format the new page header, and then the record is written.
  1158. XBy default the top-of-page format is \*(L"top\*(R", but it
  1159. Xmay be set to the
  1160. Xformat of your choice by assigning the name to the $^ variable.
  1161. XThe number of lines remaining on the current page is in variable $-, which
  1162. Xcan be set to 0 to force a new page.
  1163. X.Sp
  1164. XIf FILEHANDLE is unspecified, output goes to the current default output channel,
  1165. Xwhich starts out as
  1166. X.I STDOUT
  1167. Xbut may be changed by the
  1168. X.I select
  1169. Xoperator.
  1170. XIf the FILEHANDLE is an EXPR, then the expression is evaluated and the
  1171. Xresulting string is used to look up the name of the FILEHANDLE at run time.
  1172. XFor more on formats, see the section on formats later on.
  1173. X.Sp
  1174. XNote that write is NOT the opposite of read.
  1175. X''' Beginning of part 4
  1176. X''' $RCSfile: perl.man,v $$Revision: 4.0.1.1 $$Date: 91/04/11 17:50:44 $
  1177. X'''
  1178. X''' $Log:    perl.man,v $
  1179. X''' Revision 4.0.1.1  91/04/11  17:50:44  lwall
  1180. X''' patch1: fixed some typos
  1181. X''' 
  1182. X''' Revision 4.0  91/03/20  01:38:08  lwall
  1183. X''' 4.0 baseline.
  1184. X''' 
  1185. X''' Revision 3.0.1.14  91/01/11  18:18:53  lwall
  1186. X''' patch42: started an addendum and errata section in the man page
  1187. X''' 
  1188. X''' Revision 3.0.1.13  90/11/10  01:51:00  lwall
  1189. X''' patch38: random cleanup
  1190. X''' 
  1191. X''' Revision 3.0.1.12  90/10/20  02:15:43  lwall
  1192. X''' patch37: patch37: fixed various typos in man page
  1193. X''' 
  1194. X''' Revision 3.0.1.11  90/10/16  10:04:28  lwall
  1195. X''' patch29: added @###.## fields to format
  1196. X''' 
  1197. X''' Revision 3.0.1.10  90/08/09  04:47:35  lwall
  1198. X''' patch19: added require operator
  1199. X''' patch19: added numeric interpretation of $]
  1200. X''' 
  1201. X''' Revision 3.0.1.9  90/08/03  11:15:58  lwall
  1202. X''' patch19: Intermediate diffs for Randal
  1203. X''' 
  1204. X''' Revision 3.0.1.8  90/03/27  16:19:31  lwall
  1205. X''' patch16: MSDOS support
  1206. X''' 
  1207. X''' Revision 3.0.1.7  90/03/14  12:29:50  lwall
  1208. X''' patch15: man page falsely states that you can't subscript array values
  1209. X''' 
  1210. X''' Revision 3.0.1.6  90/03/12  16:54:04  lwall
  1211. X''' patch13: improved documentation of *name
  1212. X''' 
  1213. X''' Revision 3.0.1.5  90/02/28  18:01:52  lwall
  1214. X''' patch9: $0 is now always the command name
  1215. X''' 
  1216. X''' Revision 3.0.1.4  89/12/21  20:12:39  lwall
  1217. X''' patch7: documented that package'filehandle works as well as $package'variable
  1218. X''' patch7: documented which identifiers are always in package main
  1219. X''' 
  1220. X''' Revision 3.0.1.3  89/11/17  15:32:25  lwall
  1221. X''' patch5: fixed some manual typos and indent problems
  1222. X''' patch5: clarified difference between $! and $@
  1223. X''' 
  1224. X''' Revision 3.0.1.2  89/11/11  04:46:40  lwall
  1225. X''' patch2: made some line breaks depend on troff vs. nroff
  1226. X''' patch2: clarified operation of ^ and $ when $* is false
  1227. X''' 
  1228. X''' Revision 3.0.1.1  89/10/26  23:18:43  lwall
  1229. X''' patch1: documented the desirability of unnecessary parentheses
  1230. X''' 
  1231. X''' Revision 3.0  89/10/18  15:21:55  lwall
  1232. X''' 3.0 baseline
  1233. X''' 
  1234. X.Sh "Precedence"
  1235. X.I Perl
  1236. Xoperators have the following associativity and precedence:
  1237. X.nf
  1238. X
  1239. Xnonassoc\h'|1i'print printf exec system sort reverse
  1240. X\h'1.5i'chmod chown kill unlink utime die return
  1241. Xleft\h'|1i',
  1242. Xright\h'|1i'= += \-= *= etc.
  1243. Xright\h'|1i'?:
  1244. Xnonassoc\h'|1i'.\|.
  1245. Xleft\h'|1i'||
  1246. Xleft\h'|1i'&&
  1247. Xleft\h'|1i'| ^
  1248. Xleft\h'|1i'&
  1249. Xnonassoc\h'|1i'== != <=> eq ne cmp
  1250. Xnonassoc\h'|1i'< > <= >= lt gt le ge
  1251. Xnonassoc\h'|1i'chdir exit eval reset sleep rand umask
  1252. Xnonassoc\h'|1i'\-r \-w \-x etc.
  1253. Xleft\h'|1i'<< >>
  1254. Xleft\h'|1i'+ \- .
  1255. Xleft\h'|1i'* / % x
  1256. Xleft\h'|1i'=~ !~ 
  1257. Xright\h'|1i'! ~ and unary minus
  1258. Xright\h'|1i'**
  1259. Xnonassoc\h'|1i'++ \-\|\-
  1260. Xleft\h'|1i'\*(L'(\*(R'
  1261. X
  1262. X.fi
  1263. XAs mentioned earlier, if any list operator (print, etc.) or
  1264. Xany unary operator (chdir, etc.)
  1265. Xis followed by a left parenthesis as the next token on the same line,
  1266. Xthe operator and arguments within parentheses are taken to
  1267. Xbe of highest precedence, just like a normal function call.
  1268. XExamples:
  1269. X.nf
  1270. X
  1271. X    chdir $foo || die;\h'|3i'# (chdir $foo) || die
  1272. X    chdir($foo) || die;\h'|3i'# (chdir $foo) || die
  1273. X    chdir ($foo) || die;\h'|3i'# (chdir $foo) || die
  1274. X    chdir +($foo) || die;\h'|3i'# (chdir $foo) || die
  1275. X
  1276. Xbut, because * is higher precedence than ||:
  1277. X
  1278. X    chdir $foo * 20;\h'|3i'# chdir ($foo * 20)
  1279. X    chdir($foo) * 20;\h'|3i'# (chdir $foo) * 20
  1280. X    chdir ($foo) * 20;\h'|3i'# (chdir $foo) * 20
  1281. X    chdir +($foo) * 20;\h'|3i'# chdir ($foo * 20)
  1282. X
  1283. X    rand 10 * 20;\h'|3i'# rand (10 * 20)
  1284. X    rand(10) * 20;\h'|3i'# (rand 10) * 20
  1285. X    rand (10) * 20;\h'|3i'# (rand 10) * 20
  1286. X    rand +(10) * 20;\h'|3i'# rand (10 * 20)
  1287. X
  1288. X.fi
  1289. XIn the absence of parentheses,
  1290. Xthe precedence of list operators such as print, sort or chmod is
  1291. Xeither very high or very low depending on whether you look at the left
  1292. Xside of operator or the right side of it.
  1293. XFor example, in
  1294. X.nf
  1295. X
  1296. X    @ary = (1, 3, sort 4, 2);
  1297. X    print @ary;        # prints 1324
  1298. X
  1299. X.fi
  1300. Xthe commas on the right of the sort are evaluated before the sort, but
  1301. Xthe commas on the left are evaluated after.
  1302. XIn other words, list operators tend to gobble up all the arguments that
  1303. Xfollow them, and then act like a simple term with regard to the preceding
  1304. Xexpression.
  1305. XNote that you have to be careful with parens:
  1306. X.nf
  1307. X
  1308. X.ne 3
  1309. X    # These evaluate exit before doing the print:
  1310. X    print($foo, exit);    # Obviously not what you want.
  1311. X    print $foo, exit;    # Nor is this.
  1312. X
  1313. X.ne 4
  1314. X    # These do the print before evaluating exit:
  1315. X    (print $foo), exit;    # This is what you want.
  1316. X    print($foo), exit;    # Or this.
  1317. X    print ($foo), exit;    # Or even this.
  1318. X
  1319. XAlso note that
  1320. X
  1321. X    print ($foo & 255) + 1, "\en";
  1322. X
  1323. X.fi
  1324. Xprobably doesn't do what you expect at first glance.
  1325. X.Sh "Subroutines"
  1326. XA subroutine may be declared as follows:
  1327. X.nf
  1328. X
  1329. X    sub NAME BLOCK
  1330. X
  1331. X.fi
  1332. X.PP
  1333. XAny arguments passed to the routine come in as array @_,
  1334. Xthat is ($_[0], $_[1], .\|.\|.).
  1335. XThe array @_ is a local array, but its values are references to the
  1336. Xactual scalar parameters.
  1337. XThe return value of the subroutine is the value of the last expression
  1338. Xevaluated, and can be either an array value or a scalar value.
  1339. XAlternately, a return statement may be used to specify the returned value and
  1340. Xexit the subroutine.
  1341. XTo create local variables see the
  1342. X.I local
  1343. Xoperator.
  1344. X.PP
  1345. XA subroutine is called using the
  1346. X.I do
  1347. Xoperator or the & operator.
  1348. X.nf
  1349. X
  1350. X.ne 12
  1351. XExample:
  1352. X
  1353. X    sub MAX {
  1354. X        local($max) = pop(@_);
  1355. X        foreach $foo (@_) {
  1356. X            $max = $foo \|if \|$max < $foo;
  1357. X        }
  1358. X        $max;
  1359. X    }
  1360. X
  1361. X    .\|.\|.
  1362. X    $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  1363. X
  1364. X.ne 21
  1365. XExample:
  1366. X
  1367. X    # get a line, combining continuation lines
  1368. X    #  that start with whitespace
  1369. X    sub get_line {
  1370. X        $thisline = $lookahead;
  1371. X        line: while ($lookahead = <STDIN>) {
  1372. X            if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
  1373. X                $thisline \|.= \|$lookahead;
  1374. X            }
  1375. X            else {
  1376. X                last line;
  1377. X            }
  1378. X        }
  1379. X        $thisline;
  1380. X    }
  1381. X
  1382. X    $lookahead = <STDIN>;    # get first line
  1383. X    while ($_ = do get_line(\|)) {
  1384. X        .\|.\|.
  1385. X    }
  1386. X
  1387. X.fi
  1388. X.nf
  1389. X.ne 6
  1390. XUse array assignment to a local list to name your formal arguments:
  1391. X
  1392. X    sub maybeset {
  1393. X        local($key, $value) = @_;
  1394. X        $foo{$key} = $value unless $foo{$key};
  1395. X    }
  1396. X
  1397. X.fi
  1398. XThis also has the effect of turning call-by-reference into call-by-value,
  1399. Xsince the assignment copies the values.
  1400. X.Sp
  1401. XSubroutines may be called recursively.
  1402. XIf a subroutine is called using the & form, the argument list is optional.
  1403. XIf omitted, no @_ array is set up for the subroutine; the @_ array at the
  1404. Xtime of the call is visible to subroutine instead.
  1405. X.nf
  1406. X
  1407. X    do foo(1,2,3);        # pass three arguments
  1408. X    &foo(1,2,3);        # the same
  1409. X
  1410. X    do foo();        # pass a null list
  1411. X    &foo();            # the same
  1412. X    &foo;            # pass no arguments\*(--more efficient
  1413. X
  1414. X.fi
  1415. X.Sh "Passing By Reference"
  1416. XSometimes you don't want to pass the value of an array to a subroutine but
  1417. Xrather the name of it, so that the subroutine can modify the global copy
  1418. Xof it rather than working with a local copy.
  1419. XIn perl you can refer to all the objects of a particular name by prefixing
  1420. Xthe name with a star: *foo.
  1421. XWhen evaluated, it produces a scalar value that represents all the objects
  1422. Xof that name, including any filehandle, format or subroutine.
  1423. XWhen assigned to within a local() operation, it causes the name mentioned
  1424. Xto refer to whatever * value was assigned to it.
  1425. XExample:
  1426. X.nf
  1427. X
  1428. X    sub doubleary {
  1429. X        local(*someary) = @_;
  1430. X        foreach $elem (@someary) {
  1431. X        $elem *= 2;
  1432. X        }
  1433. X    }
  1434. X    do doubleary(*foo);
  1435. X    do doubleary(*bar);
  1436. X
  1437. X.fi
  1438. XAssignment to *name is currently recommended only inside a local().
  1439. XYou can actually assign to *name anywhere, but the previous referent of
  1440. X*name may be stranded forever.
  1441. XThis may or may not bother you.
  1442. X.Sp
  1443. !STUFFY!FUNK!
  1444. echo " "
  1445. echo "End of kit 8 (of 36)"
  1446. cat /dev/null >kit8isdone
  1447. run=''
  1448. config=''
  1449. for iskit in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36; do
  1450.     if test -f kit${iskit}isdone; then
  1451.     run="$run $iskit"
  1452.     else
  1453.     todo="$todo $iskit"
  1454.     fi
  1455. done
  1456. case $todo in
  1457.     '')
  1458.     echo "You have run all your kits.  Please read README and then type Configure."
  1459.     for combo in *:AA; do
  1460.         if test -f "$combo"; then
  1461.         realfile=`basename $combo :AA`
  1462.         cat $realfile:[A-Z][A-Z] >$realfile
  1463.         rm -rf $realfile:[A-Z][A-Z]
  1464.         fi
  1465.     done
  1466.     rm -rf kit*isdone
  1467.     chmod 755 Configure
  1468.     ;;
  1469.     *)  echo "You have run$run."
  1470.     echo "You still need to run$todo."
  1471.     ;;
  1472. esac
  1473. : Someone might mail this, so...
  1474. exit
  1475.  
  1476. exit 0 # Just in case...
  1477. -- 
  1478. Kent Landfield                   INTERNET: kent@sparky.IMD.Sterling.COM
  1479. Sterling Software, IMD           UUCP:     uunet!sparky!kent
  1480. Phone:    (402) 291-8300         FAX:      (402) 291-4362
  1481. Please send comp.sources.misc-related mail to kent@uunet.uu.net.
  1482.