home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume20 / perl3.0 / part08 < prev    next >
Encoding:
Internet Message Format  |  1989-10-30  |  48.7 KB

  1. Subject:  v20i091:  Perl, a language with features of C/sed/awk/shell/etc, Part08/24
  2. Newsgroups: comp.sources.unix
  3. Sender: sources
  4. Approved: rsalz@uunet.UU.NET
  5.  
  6. Submitted-by: Larry Wall <lwall@jpl-devvax.jpl.nasa.gov>
  7. Posting-number: Volume 20, Issue 91
  8. Archive-name: perl3.0/part08
  9.  
  10. #! /bin/sh
  11.  
  12. # Make a new directory for the perl sources, cd to it, and run kits 1
  13. # thru 24 through sh.  When all 24 kits have been run, read README.
  14.  
  15. echo "This is perl 3.0 kit 8 (of 24).  If kit 8 is complete, the line"
  16. echo '"'"End of kit 8 (of 24)"'" will echo at the end.'
  17. echo ""
  18. export PATH || (echo "You didn't use sh, you clunch." ; kill $$)
  19. mkdir t 2>/dev/null
  20. echo Extracting perl.man.3
  21. sed >perl.man.3 <<'!STUFFY!FUNK!' -e 's/X//'
  22. X''' Beginning of part 3
  23. X''' $Header: perl.man.3,v 3.0 89/10/18 15:21:46 lwall Locked $
  24. X'''
  25. X''' $Log:    perl.man.3,v $
  26. X''' Revision 3.0  89/10/18  15:21:46  lwall
  27. X''' 3.0 baseline
  28. X''' 
  29. X.Ip "next LABEL" 8 8
  30. X.Ip "next" 8
  31. XThe
  32. X.I next
  33. Xcommand is like the
  34. X.I continue
  35. Xstatement in C; it starts the next iteration of the loop:
  36. X.nf
  37. X
  38. X.ne 4
  39. X    line: while (<STDIN>) {
  40. X        next line if /\|^#/;    # discard comments
  41. X        .\|.\|.
  42. X    }
  43. X
  44. X.fi
  45. XNote that if there were a
  46. X.I continue
  47. Xblock on the above, it would get executed even on discarded lines.
  48. XIf the LABEL is omitted, the command refers to the innermost enclosing loop.
  49. X.Ip "oct(EXPR)" 8 4
  50. X.Ip "oct EXPR" 8
  51. XReturns the decimal value of EXPR interpreted as an octal string.
  52. X(If EXPR happens to start off with 0x, interprets it as a hex string instead.)
  53. XThe following will handle decimal, octal and hex in the standard notation:
  54. X.nf
  55. X
  56. X    $val = oct($val) if $val =~ /^0/;
  57. X
  58. X.fi
  59. XIf EXPR is omitted, uses $_.
  60. X.Ip "open(FILEHANDLE,EXPR)" 8 8
  61. X.Ip "open(FILEHANDLE)" 8
  62. X.Ip "open FILEHANDLE" 8
  63. XOpens the file whose filename is given by EXPR, and associates it with
  64. XFILEHANDLE.
  65. XIf FILEHANDLE is an expression, its value is used as the name of the
  66. Xreal filehandle wanted.
  67. XIf EXPR is omitted, the scalar variable of the same name as the FILEHANDLE
  68. Xcontains the filename.
  69. XIf the filename begins with \*(L"<\*(R" or nothing, the file is opened for
  70. Xinput.
  71. XIf the filename begins with \*(L">\*(R", the file is opened for output.
  72. XIf the filename begins with \*(L">>\*(R", the file is opened for appending.
  73. X(You can put a \'+\' in front of the \'>\' or \'<\' to indicate that you
  74. Xwant both read and write access to the file.)
  75. XIf the filename begins with \*(L"|\*(R", the filename is interpreted
  76. Xas a command to which output is to be piped, and if the filename ends
  77. Xwith a \*(L"|\*(R", the filename is interpreted as command which pipes
  78. Xinput to us.
  79. X(You may not have a command that pipes both in and out.)
  80. XOpening \'\-\' opens
  81. X.I STDIN
  82. Xand opening \'>\-\' opens
  83. X.IR STDOUT .
  84. XOpen returns non-zero upon success, the undefined value otherwise.
  85. XIf the open involved a pipe, the return value happens to be the pid
  86. Xof the subprocess.
  87. XExamples:
  88. X.nf
  89. X    
  90. X.ne 3
  91. X    $article = 100;
  92. X    open article || die "Can't find article $article: $!\en";
  93. X    while (<article>) {\|.\|.\|.
  94. X
  95. X    open(LOG, \'>>/usr/spool/news/twitlog\'\|);    # (log is reserved)
  96. X
  97. X    open(article, "caesar <$article |"\|);        # decrypt article
  98. X
  99. X    open(extract, "|sort >/tmp/Tmp$$"\|);        # $$ is our process#
  100. X
  101. X.ne 7
  102. X    # process argument list of files along with any includes
  103. X
  104. X    foreach $file (@ARGV) {
  105. X        do process($file, \'fh00\');    # no pun intended
  106. X    }
  107. X
  108. X    sub process {
  109. X        local($filename, $input) = @_;
  110. X        $input++;        # this is a string increment
  111. X        unless (open($input, $filename)) {
  112. X            print STDERR "Can't open $filename: $!\en";
  113. X            return;
  114. X        }
  115. X        while (<$input>) {        # note the use of indirection
  116. X            if (/^#include "(.*)"/) {
  117. X                do process($1, $input);
  118. X                next;
  119. X            }
  120. X            .\|.\|.        # whatever
  121. X        }
  122. X    }
  123. X
  124. X.fi
  125. XYou may also, in the Bourne shell tradition, specify an EXPR beginning
  126. Xwith \*(L">&\*(R", in which case the rest of the string
  127. Xis interpreted as the name of a filehandle
  128. X(or file descriptor, if numeric) which is to be duped and opened.
  129. XHere is a script that saves, redirects, and restores
  130. X.I STDOUT
  131. Xand
  132. X.IR STDIN :
  133. X.nf
  134. X
  135. X.ne 21
  136. X    #!/usr/bin/perl
  137. X    open(SAVEOUT, ">&STDOUT");
  138. X    open(SAVEERR, ">&STDERR");
  139. X
  140. X    open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  141. X    open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  142. X
  143. X    select(STDERR); $| = 1;        # make unbuffered
  144. X    select(STDOUT); $| = 1;        # make unbuffered
  145. X
  146. X    print STDOUT "stdout 1\en";    # this works for
  147. X    print STDERR "stderr 1\en";     # subprocesses too
  148. X
  149. X    close(STDOUT);
  150. X    close(STDERR);
  151. X
  152. X    open(STDOUT, ">&SAVEOUT");
  153. X    open(STDERR, ">&SAVEERR");
  154. X
  155. X    print STDOUT "stdout 2\en";
  156. X    print STDERR "stderr 2\en";
  157. X
  158. X.fi
  159. XIf you open a pipe on the command \*(L"\-\*(R", i.e. either \*(L"|\-\*(R" or \*(L"\-|\*(R",
  160. Xthen there is an implicit fork done, and the return value of open
  161. Xis the pid of the child within the parent process, and 0 within the child
  162. Xprocess.
  163. X(Use defined($pid) to determine if the open was successful.)
  164. XThe filehandle behaves normally for the parent, but i/o to that
  165. Xfilehandle is piped from/to the
  166. X.IR STDOUT / STDIN
  167. Xof the child process.
  168. XIn the child process the filehandle isn't opened\*(--i/o happens from/to
  169. Xthe new
  170. X.I STDOUT
  171. Xor
  172. X.IR STDIN .
  173. XTypically this is used like the normal piped open when you want to exercise
  174. Xmore control over just how the pipe command gets executed, such as when
  175. Xyou are running setuid, and don't want to have to scan shell commands
  176. Xfor metacharacters.
  177. XThe following pairs are equivalent:
  178. X.nf
  179. X
  180. X.ne 5
  181. X    open(FOO, "|tr \'[a\-z]\' \'[A\-Z]\'");
  182. X    open(FOO, "|\-") || exec \'tr\', \'[a\-z]\', \'[A\-Z]\';
  183. X
  184. X    open(FOO, "cat \-n $file|");
  185. X    open(FOO, "\-|") || exec \'cat\', \'\-n\', $file;
  186. X
  187. X.fi
  188. XExplicitly closing any piped filehandle causes the parent process to wait for the
  189. Xchild to finish, and returns the status value in $?.
  190. X.Ip "opendir(DIRHANDLE,EXPR)" 8 3
  191. XOpens a directory named EXPR for processing by readdir(), telldir(), seekdir(),
  192. Xrewinddir() and closedir().
  193. XReturns true if successful.
  194. XDIRHANDLEs have their own namespace separate from FILEHANDLEs.
  195. X.Ip "ord(EXPR)" 8 4
  196. X.Ip "ord EXPR" 8
  197. XReturns the ascii value of the first character of EXPR.
  198. XIf EXPR is omitted, uses $_.
  199. X.Ip "pack(TEMPLATE,LIST)" 8 4
  200. XTakes an array or list of values and packs it into a binary structure,
  201. Xreturning the string containing the structure.
  202. XThe TEMPLATE is a sequence of characters that give the order and type
  203. Xof values, as follows:
  204. X.nf
  205. X
  206. X    A    An ascii string, will be space padded.
  207. X    a    An ascii string, will be null padded.
  208. X    c    A native char value.
  209. X    C    An unsigned char value.
  210. X    s    A signed short value.
  211. X    S    An unsigned short value.
  212. X    i    A signed integer value.
  213. X    I    An unsigned integer value.
  214. X    l    A signed long value.
  215. X    L    An unsigned long value.
  216. X    n    A short in \*(L"network\*(R" order.
  217. X    N    A long in \*(L"network\*(R" order.
  218. X    p    A pointer to a string.
  219. X    x    A null byte.
  220. X
  221. X.fi
  222. XEach letter may optionally be followed by a number which gives a repeat
  223. Xcount.
  224. XWith all types except "a" and "A" the pack function will gobble up that many values
  225. Xfrom the LIST.
  226. XThe "a" and "A" types gobble just one value, but pack it as a string that long,
  227. Xpadding with nulls or spaces as necessary.
  228. X(When unpacking, "A" strips trailing spaces and nulls, but "a" does not.)
  229. XExamples:
  230. X.nf
  231. X
  232. X    $foo = pack("cccc",65,66,67,68);
  233. X    # foo eq "ABCD"
  234. X    $foo = pack("c4",65,66,67,68);
  235. X    # same thing
  236. X
  237. X    $foo = pack("ccxxcc",65,66,67,68);
  238. X    # foo eq "AB\e0\e0CD"
  239. X
  240. X    $foo = pack("s2",1,2);
  241. X    # "\e1\e0\e2\e0" on little-endian
  242. X    # "\e0\e1\e0\e2" on big-endian
  243. X
  244. X    $foo = pack("a4","abcd","x","y","z");
  245. X    # "abcd"
  246. X
  247. X    $foo = pack("aaaa","abcd","x","y","z");
  248. X    # "axyz"
  249. X
  250. X    $foo = pack("a14","abcdefg");
  251. X    # "abcdefg\e0\e0\e0\e0\e0\e0\e0"
  252. X
  253. X    $foo = pack("i9pl", gmtime());
  254. X    # a real struct tm (on my system anyway)
  255. X
  256. X.fi
  257. XThe same template may generally also be used in the unpack function.
  258. X.Ip "pop(ARRAY)" 8
  259. X.Ip "pop ARRAY" 8 6
  260. XPops and returns the last value of the array, shortening the array by 1.
  261. XHas the same effect as
  262. X.nf
  263. X
  264. X    $tmp = $ARRAY[$#ARRAY\-\|\-];
  265. X
  266. X.fi
  267. XIf there are no elements in the array, returns the undefined value.
  268. X.Ip "print(FILEHANDLE LIST)" 8 10
  269. X.Ip "print(LIST)" 8
  270. X.Ip "print FILEHANDLE LIST" 8
  271. X.Ip "print LIST" 8
  272. X.Ip "print" 8
  273. XPrints a string or a comma-separated list of strings.
  274. XReturns non-zero if successful.
  275. XFILEHANDLE may be a scalar variable name, in which case the variable contains
  276. Xthe name of the filehandle, thus introducing one level of indirection.
  277. XIf FILEHANDLE is omitted, prints by default to standard output (or to the
  278. Xlast selected output channel\*(--see select()).
  279. XIf LIST is also omitted, prints $_ to
  280. X.IR STDOUT .
  281. XTo set the default output channel to something other than
  282. X.I STDOUT
  283. Xuse the select operation.
  284. X.Ip "printf(FILEHANDLE LIST)" 8 10
  285. X.Ip "printf(LIST)" 8
  286. X.Ip "printf FILEHANDLE LIST" 8
  287. X.Ip "printf LIST" 8
  288. XEquivalent to a \*(L"print FILEHANDLE sprintf(LIST)\*(R".
  289. X.Ip "push(ARRAY,LIST)" 8 7
  290. XTreats ARRAY (@ is optional) as a stack, and pushes the values of LIST
  291. Xonto the end of ARRAY.
  292. XThe length of ARRAY increases by the length of LIST.
  293. XHas the same effect as
  294. X.nf
  295. X
  296. X    for $value (LIST) {
  297. X        $ARRAY[++$#ARRAY] = $value;
  298. X    }
  299. X
  300. X.fi
  301. Xbut is more efficient.
  302. X.Ip "q/STRING/" 8 5
  303. X.Ip "qq/STRING/" 8
  304. XThese are not really functions, but simply syntactic sugar to let you
  305. Xavoid putting too many backslashes into quoted strings.
  306. XThe q operator is a generalized single quote, and the qq operator a
  307. Xgeneralized double quote.
  308. XAny delimiter can be used in place of /, including newline.
  309. XIf the delimiter is an opening bracket or parenthesis, the final delimiter
  310. Xwill be the corresponding closing bracket or parenthesis.
  311. X(Embedded occurrences of the closing bracket need to be backslashed as usual.)
  312. XExamples:
  313. X.nf
  314. X
  315. X.ne 5
  316. X    $foo = q!I said, "You said, \'She said it.\'"!;
  317. X    $bar = q(\'This is it.\');
  318. X    $_ .= qq
  319. X*** The previous line contains the naughty word "$&".\en
  320. X        if /(ibm|apple|awk)/;      # :-)
  321. X
  322. X.fi
  323. X.Ip "rand(EXPR)" 8 8
  324. X.Ip "rand EXPR" 8
  325. X.Ip "rand" 8
  326. XReturns a random fractional number between 0 and the value of EXPR.
  327. X(EXPR should be positive.)
  328. XIf EXPR is omitted, returns a value between 0 and 1.
  329. XSee also srand().
  330. X.Ip "read(FILEHANDLE,SCALAR,LENGTH)" 8 5
  331. XAttempts to read LENGTH bytes of data into variable SCALAR from the specified
  332. XFILEHANDLE.
  333. XReturns the number of bytes actually read.
  334. XSCALAR will be grown or shrunk to the length actually read.
  335. X.Ip "readdir(DIRHANDLE)" 8 3
  336. XReturns the next directory entry for a directory opened by opendir().
  337. XIf used in an array context, returns all the rest of the entries in the
  338. Xdirectory.
  339. XIf there are no more entries, returns an undefined value in a scalar context
  340. Xor a null list in an array context.
  341. X.Ip "readlink(EXPR)" 8 6
  342. X.Ip "readlink EXPR" 8
  343. XReturns the value of a symbolic link, if symbolic links are implemented.
  344. XIf not, gives a fatal error.
  345. XIf there is some system error, returns the undefined value and sets $! (errno).
  346. XIf EXPR is omitted, uses $_.
  347. X.Ip "recv(SOCKET,SCALAR,LEN,FLAGS)" 8 4
  348. XReceives a message on a socket.
  349. XAttempts to receive LENGTH bytes of data into variable SCALAR from the specified
  350. XSOCKET filehandle.
  351. XReturns the address of the sender, or the undefined value if there's an error.
  352. XSCALAR will be grown or shrunk to the length actually read.
  353. XTakes the same flags as the system call of the same name.
  354. X.Ip "redo LABEL" 8 8
  355. X.Ip "redo" 8
  356. XThe
  357. X.I redo
  358. Xcommand restarts the loop block without evaluating the conditional again.
  359. XThe
  360. X.I continue
  361. Xblock, if any, is not executed.
  362. XIf the LABEL is omitted, the command refers to the innermost enclosing loop.
  363. XThis command is normally used by programs that want to lie to themselves
  364. Xabout what was just input:
  365. X.nf
  366. X
  367. X.ne 16
  368. X    # a simpleminded Pascal comment stripper
  369. X    # (warning: assumes no { or } in strings)
  370. X    line: while (<STDIN>) {
  371. X        while (s|\|({.*}.*\|){.*}|$1 \||) {}
  372. X        s|{.*}| \||;
  373. X        if (s|{.*| \||) {
  374. X            $front = $_;
  375. X            while (<STDIN>) {
  376. X                if (\|/\|}/\|) {    # end of comment?
  377. X                    s|^|$front{|;
  378. X                    redo line;
  379. X                }
  380. X            }
  381. X        }
  382. X        print;
  383. X    }
  384. X
  385. X.fi
  386. X.Ip "rename(OLDNAME,NEWNAME)" 8 2
  387. XChanges the name of a file.
  388. XReturns 1 for success, 0 otherwise.
  389. XWill not work across filesystem boundaries.
  390. X.Ip "reset(EXPR)" 8 6
  391. X.Ip "reset EXPR" 8
  392. X.Ip "reset" 8
  393. XGenerally used in a
  394. X.I continue
  395. Xblock at the end of a loop to clear variables and reset ?? searches
  396. Xso that they work again.
  397. XThe expression is interpreted as a list of single characters (hyphens allowed
  398. Xfor ranges).
  399. XAll variables and arrays beginning with one of those letters are reset to
  400. Xtheir pristine state.
  401. XIf the expression is omitted, one-match searches (?pattern?) are reset to
  402. Xmatch again.
  403. XOnly resets variables or searches in the current package.
  404. XAlways returns 1.
  405. XExamples:
  406. X.nf
  407. X
  408. X.ne 3
  409. X    reset \'X\';    \h'|2i'# reset all X variables
  410. X    reset \'a\-z\';\h'|2i'# reset lower case variables
  411. X    reset;    \h'|2i'# just reset ?? searches
  412. X
  413. X.fi
  414. XNote: resetting \*(L"A\-Z\*(R" is not recommended since you'll wipe out your ARGV and ENV
  415. Xarrays.
  416. X.Sp
  417. XThe use of reset on dbm associative arrays does not change the dbm file.
  418. X(It does, however, flush any entries cached by perl, which may be useful if
  419. Xyou are sharing the dbm file.
  420. XThen again, maybe not.)
  421. X.Ip "return LIST" 8 3
  422. XReturns from a subroutine with the value specified.
  423. X(Note that a subroutine can automatically return
  424. Xthe value of the last expression evaluated.
  425. XThat's the preferred method\*(--use of an explicit
  426. X.I return
  427. Xis a bit slower.)
  428. X.Ip "reverse(LIST)" 8 4
  429. X.Ip "reverse LIST" 8
  430. XReturns an array value consisting of the elements of LIST in the opposite order.
  431. X.Ip "rewinddir(DIRHANDLE)" 8 5
  432. X.Ip "rewinddir DIRHANDLE" 8
  433. XSets the current position to the beginning of the directory for the readdir() routine on DIRHANDLE.
  434. X.Ip "rindex(STR,SUBSTR)" 8 4
  435. XWorks just like index except that it
  436. Xreturns the position of the LAST occurrence of SUBSTR in STR.
  437. X.Ip "rmdir(FILENAME)" 8 4
  438. X.Ip "rmdir FILENAME" 8
  439. XDeletes the directory specified by FILENAME if it is empty.
  440. XIf it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
  441. XIf FILENAME is omitted, uses $_.
  442. X.Ip "s/PATTERN/REPLACEMENT/gieo" 8 3
  443. XSearches a string for a pattern, and if found, replaces that pattern with the
  444. Xreplacement text and returns the number of substitutions made.
  445. XOtherwise it returns false (0).
  446. XThe \*(L"g\*(R" is optional, and if present, indicates that all occurrences
  447. Xof the pattern are to be replaced.
  448. XThe \*(L"i\*(R" is also optional, and if present, indicates that matching
  449. Xis to be done in a case-insensitive manner.
  450. XThe \*(L"e\*(R" is likewise optional, and if present, indicates that
  451. Xthe replacement string is to be evaluated as an expression rather than just
  452. Xas a double-quoted string.
  453. XAny delimiter may replace the slashes; if single quotes are used, no
  454. Xinterpretation is done on the replacement string (the e modifier overrides
  455. Xthis, however).
  456. XIf no string is specified via the =~ or !~ operator,
  457. Xthe $_ string is searched and modified.
  458. X(The string specified with =~ must be a scalar variable, an array element,
  459. Xor an assignment to one of those, i.e. an lvalue.)
  460. XIf the pattern contains a $ that looks like a variable rather than an
  461. Xend-of-string test, the variable will be interpolated into the pattern at
  462. Xrun-time.
  463. XIf you only want the pattern compiled once the first time the variable is
  464. Xinterpolated, add an \*(L"o\*(R" at the end.
  465. XSee also the section on regular expressions.
  466. XExamples:
  467. X.nf
  468. X
  469. X    s/\|\e\|bgreen\e\|b/mauve/g;        # don't change wintergreen
  470. X
  471. X    $path \|=~ \|s|\|/usr/bin|\|/usr/local/bin|;
  472. X
  473. X    s/Login: $foo/Login: $bar/; # run-time pattern
  474. X
  475. X    ($foo = $bar) =~ s/bar/foo/;
  476. X
  477. X    $_ = \'abc123xyz\';
  478. X    s/\ed+/$&*2/e;        # yields \*(L'abc246xyz\*(R'
  479. X    s/\ed+/sprintf("%5d",$&)/e;    # yields \*(L'abc  246xyz\*(R'
  480. X    s/\ew/$& x 2/eg;        # yields \*(L'aabbcc  224466xxyyzz\*(R'
  481. X
  482. X    s/\|([^ \|]*\|) *\|([^ \|]*\|)\|/\|$2 $1/;    # reverse 1st two fields
  483. X
  484. X.fi
  485. X(Note the use of $ instead of \|\e\| in the last example.  See section
  486. Xon regular expressions.)
  487. X.Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
  488. XRandomly positions the file pointer for FILEHANDLE, just like the fseek()
  489. Xcall of stdio.
  490. XFILEHANDLE may be an expression whose value gives the name of the filehandle.
  491. XReturns 1 upon success, 0 otherwise.
  492. X.Ip "seekdir(DIRHANDLE,POS)" 8 3
  493. XSets the current position for the readdir() routine on DIRHANDLE.
  494. XPOS must be a value returned by seekdir().
  495. XHas the same caveats about possible directory compaction as the corresponding
  496. Xsystem library routine.
  497. X.Ip "select(FILEHANDLE)" 8 3
  498. X.Ip "select" 8 3
  499. XReturns the currently selected filehandle.
  500. XSets the current default filehandle for output, if FILEHANDLE is supplied.
  501. XThis has two effects: first, a
  502. X.I write
  503. Xor a
  504. X.I print
  505. Xwithout a filehandle will default to this FILEHANDLE.
  506. XSecond, references to variables related to output will refer to this output
  507. Xchannel.
  508. XFor example, if you have to set the top of form format for more than
  509. Xone output channel, you might do the following:
  510. X.nf
  511. X
  512. X.ne 4
  513. X    select(REPORT1);
  514. X    $^ = \'report1_top\';
  515. X    select(REPORT2);
  516. X    $^ = \'report2_top\';
  517. X
  518. X.fi
  519. XFILEHANDLE may be an expression whose value gives the name of the actual filehandle.
  520. XThus:
  521. X.nf
  522. X
  523. X    $oldfh = select(STDERR); $| = 1; select($oldfh);
  524. X
  525. X.fi
  526. X.Ip "select(RBITS,WBITS,EBITS,TIMEOUT)" 8 3
  527. XThis calls the select system call with the bitmasks specified, which can
  528. Xbe constructed using fileno() and vec(), along these lines:
  529. X.nf
  530. X
  531. X    $rin = $win = $ein = '';
  532. X    vec($rin,fileno(STDIN),1) = 1;
  533. X    vec($win,fileno(STDOUT),1) = 1;
  534. X    $ein = $rin | $win;
  535. X
  536. X.fi
  537. XIf you want to select on many filehandles you might wish to write a subroutine:
  538. X.nf
  539. X
  540. X    sub fhbits {
  541. X        local(@fhlist) = split(' ',$_[0]);
  542. X        local($bits);
  543. X        for (@fhlist) {
  544. X        vec($bits,fileno($_),1) = 1;
  545. X        }
  546. X        $bits;
  547. X    }
  548. X    $rin = &fhbits('STDIN TTY SOCK');
  549. X
  550. X.fi
  551. XThe usual idiom is:
  552. X.nf
  553. X
  554. X    ($nfound,$timeleft) =
  555. X      select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  556. X
  557. Xor to block until something becomes ready:
  558. X
  559. X    $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
  560. X
  561. X.fi
  562. XAny of the bitmasks can also be undef.
  563. XThe timeout, if specified, is in seconds, which may be fractional.
  564. X.Ip "setpgrp(PID,PGRP)" 8 4
  565. XSets the current process group for the specified PID, 0 for the current
  566. Xprocess.
  567. XWill produce a fatal error if used on a machine that doesn't implement
  568. Xsetpgrp(2).
  569. X.Ip "send(SOCKET,MSG,FLAGS,TO)" 8 4
  570. X.Ip "send(SOCKET,MSG,FLAGS)" 8
  571. XSends a message on a socket.
  572. XTakes the same flags as the system call of the same name.
  573. XOn unconnected sockets you must specify a destination to send TO.
  574. XReturns the number of characters sent, or the undefined value if
  575. Xthere is an error.
  576. X.Ip "setpriority(WHICH,WHO,PRIORITY)" 8 4
  577. XSets the current priority for a process, a process group, or a user.
  578. X(See setpriority(2).)
  579. XWill produce a fatal error if used on a machine that doesn't implement
  580. Xsetpriority(2).
  581. X.Ip "setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)" 8 3
  582. XSets the socket option requested.
  583. XReturns undefined if there is an error.
  584. XOPTVAL may be specified as undef if you don't want to pass an argument.
  585. X.Ip "shift(ARRAY)" 8 6
  586. X.Ip "shift ARRAY" 8
  587. X.Ip "shift" 8
  588. XShifts the first value of the array off and returns it,
  589. Xshortening the array by 1 and moving everything down.
  590. XIf there are no elements in the array, returns the undefined value.
  591. XIf ARRAY is omitted, shifts the @ARGV array in the main program, and the @_
  592. Xarray in subroutines.
  593. XSee also unshift(), push() and pop().
  594. XShift() and unshift() do the same thing to the left end of an array that push()
  595. Xand pop() do to the right end.
  596. X.Ip "shutdown(SOCKET,HOW)" 8 3
  597. XShuts down a socket connection in the manner indicated by HOW, which has
  598. Xthe same interpretation as in the system call of the same name.
  599. X.Ip "sin(EXPR)" 8 4
  600. X.Ip "sin EXPR" 8
  601. XReturns the sine of EXPR (expressed in radians).
  602. XIf EXPR is omitted, returns sine of $_.
  603. X.Ip "sleep(EXPR)" 8 6
  604. X.Ip "sleep EXPR" 8
  605. X.Ip "sleep" 8
  606. XCauses the script to sleep for EXPR seconds, or forever if no EXPR.
  607. XMay be interrupted by sending the process a SIGALARM.
  608. XReturns the number of seconds actually slept.
  609. X.Ip "socket(SOCKET,DOMAIN,TYPE,PROTOCOL)" 8 3
  610. XOpens a socket of the specified kind and attaches it to filehandle SOCKET.
  611. XDOMAIN, TYPE and PROTOCOL are specified the same as for the system call
  612. Xof the same name.
  613. XYou may need to run makelib on sys/socket.h to get the proper values handy
  614. Xin a perl library file.
  615. XReturn true if successful.
  616. XSee the example in the section on Interprocess Communication.
  617. X.Ip "socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)" 8 3
  618. XCreates an unnamed pair of sockets in the specified domain, of the specified
  619. Xtype.
  620. XDOMAIN, TYPE and PROTOCOL are specified the same as for the system call
  621. Xof the same name.
  622. XIf unimplemented, yields a fatal error.
  623. XReturn true if successful.
  624. X.Ip "sort(SUBROUTINE LIST)" 8 9
  625. X.Ip "sort(LIST)" 8
  626. X.Ip "sort SUBROUTINE LIST" 8
  627. X.Ip "sort LIST" 8
  628. XSorts the LIST and returns the sorted array value.
  629. XNonexistent values of arrays are stripped out.
  630. XIf SUBROUTINE is omitted, sorts in standard string comparison order.
  631. XIf SUBROUTINE is specified, gives the name of a subroutine that returns
  632. Xan integer less than, equal to, or greater than 0,
  633. Xdepending on how the elements of the array are to be ordered.
  634. XIn the interests of efficiency the normal calling code for subroutines
  635. Xis bypassed, with the following effects: the subroutine may not be a recursive
  636. Xsubroutine, and the two elements to be compared are passed into the subroutine
  637. Xnot via @_ but as $a and $b (see example below).
  638. XThey are passed by reference so don't modify $a and $b.
  639. XSUBROUTINE may be a scalar variable name, in which case the value provides
  640. Xthe name of the subroutine to use.
  641. XExamples:
  642. X.nf
  643. X
  644. X.ne 4
  645. X    sub byage {
  646. X        $age{$a} - $age{$b};    # presuming integers
  647. X    }
  648. X    @sortedclass = sort byage @class;
  649. X
  650. X.ne 9
  651. X    sub reverse { $a lt $b ? 1 : $a gt $b ? \-1 : 0; }
  652. X    @harry = (\'dog\',\'cat\',\'x\',\'Cain\',\'Abel\');
  653. X    @george = (\'gone\',\'chased\',\'yz\',\'Punished\',\'Axed\');
  654. X    print sort @harry;
  655. X        # prints AbelCaincatdogx
  656. X    print sort reverse @harry;
  657. X        # prints xdogcatCainAbel
  658. X    print sort @george, \'to\', @harry;
  659. X        # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  660. X
  661. X.fi
  662. X.Ip "split(/PATTERN/,EXPR,LIMIT)" 8 8
  663. X.Ip "split(/PATTERN/,EXPR)" 8 8
  664. X.Ip "split(/PATTERN/)" 8
  665. X.Ip "split" 8
  666. XSplits a string into an array of strings, and returns it.
  667. X(If not in an array context, returns the number of fields found and splits
  668. Xinto the @_ array.)
  669. XIf EXPR is omitted, splits the $_ string.
  670. XIf PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
  671. XAnything matching PATTERN is taken to be a delimiter separating the fields.
  672. X(Note that the delimiter may be longer than one character.)
  673. XIf LIMIT is specified, splits into no more than that many fields (though it
  674. Xmay split into fewer).
  675. XIf LIMIT is unspecified, trailing null fields are stripped (which
  676. Xpotential users of pop() would do well to remember).
  677. XA pattern matching the null string (not to be confused with a null pattern,
  678. Xwhich is one member of the set of patterns matching a null string)
  679. Xwill split the value of EXPR into separate characters at each point it
  680. Xmatches that way.
  681. XFor example:
  682. X.nf
  683. X
  684. X    print join(\':\', split(/ */, \'hi there\'));
  685. X
  686. X.fi
  687. Xproduces the output \*(L'h:i:t:h:e:r:e\*(R'.
  688. X.P
  689. XThe NUM parameter can be used to partially split a line
  690. X.nf
  691. X
  692. X    ($login, $passwd, $remainder) = split(\|/\|:\|/\|, $_, 3);
  693. X
  694. X.fi
  695. X(When assigning to a list, if NUM is omitted, perl supplies a NUM one
  696. Xlarger than the number of variables in the list, to avoid unnecessary work.
  697. XFor the list above NUM would have been 4 by default.
  698. XIn time critical applications it behooves you not to split into
  699. Xmore fields than you really need.)
  700. X.Sp
  701. XIf the PATTERN contains parentheses, additional array elements are created
  702. Xfrom each matching substring in the delimiter.
  703. X.Sp
  704. X    split(/([,-])/,"1-10,20");
  705. X.Sp
  706. Xproduces the array value
  707. X.Sp
  708. X    (1,'-',10,',',20)
  709. X.Sp
  710. XThe pattern /PATTERN/ may be replaced with an expression to specify patterns
  711. Xthat vary at runtime.
  712. X(To do runtime compilation only once, use /$variable/o.)
  713. XAs a special case, specifying a space (\'\ \') will split on white space
  714. Xjust as split with no arguments does, but leading white space does NOT
  715. Xproduce a null first field.
  716. XThus, split(\'\ \') can be used to emulate
  717. X.IR awk 's
  718. Xdefault behavior, whereas
  719. Xsplit(/\ /) will give you as many null initial fields as there are
  720. Xleading spaces.
  721. X.Sp
  722. XExample:
  723. X.nf
  724. X
  725. X.ne 5
  726. X    open(passwd, \'/etc/passwd\');
  727. X    while (<passwd>) {
  728. X.ie t \{\
  729. X        ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(\|/\|:\|/\|);
  730. X'br\}
  731. X.el \{\
  732. X        ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  733. X            = split(\|/\|:\|/\|);
  734. X'br\}
  735. X        .\|.\|.
  736. X    }
  737. X
  738. X.fi
  739. X(Note that $shell above will still have a newline on it.  See chop().)
  740. XSee also
  741. X.IR join .
  742. X.Ip "sprintf(FORMAT,LIST)" 8 4
  743. XReturns a string formatted by the usual printf conventions.
  744. XThe * character is not supported.
  745. X.Ip "sqrt(EXPR)" 8 4
  746. X.Ip "sqrt EXPR" 8
  747. XReturn the square root of EXPR.
  748. XIf EXPR is omitted, returns square root of $_.
  749. X.Ip "srand(EXPR)" 8 4
  750. X.Ip "srand EXPR" 8
  751. XSets the random number seed for the
  752. X.I rand
  753. Xoperator.
  754. XIf EXPR is omitted, does srand(time).
  755. X.Ip "stat(FILEHANDLE)" 8 6
  756. X.Ip "stat FILEHANDLE" 8
  757. X.Ip "stat(EXPR)" 8
  758. XReturns a 13-element array giving the statistics for a file, either the file
  759. Xopened via FILEHANDLE, or named by EXPR.
  760. XTypically used as follows:
  761. X.nf
  762. X
  763. X.ne 3
  764. X    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  765. X       $atime,$mtime,$ctime,$blksize,$blocks)
  766. X           = stat($filename);
  767. X
  768. X.fi
  769. XIf stat is passed the special filehandle consisting of an underline,
  770. Xno stat is done, but the current contents of the stat structure from
  771. Xthe last stat or filetest are returned.
  772. XExample:
  773. X.nf
  774. X
  775. X.ne 3
  776. X    if (-x $file && (($d) = stat(_)) && $d < 0) {
  777. X        print "$file is executable NFS file\en";
  778. X    }
  779. X
  780. X.fi
  781. X.Ip "study(SCALAR)" 8 6
  782. X.Ip "study SCALAR" 8
  783. X.Ip "study"
  784. XTakes extra time to study SCALAR ($_ if unspecified) in anticipation of
  785. Xdoing many pattern matches on the string before it is next modified.
  786. XThis may or may not save time, depending on the nature and number of patterns
  787. Xyou are searching on, and on the distribution of character frequencies in
  788. Xthe string to be searched\*(--you probably want to compare runtimes with and
  789. Xwithout it to see which runs faster.
  790. XThose loops which scan for many short constant strings (including the constant
  791. Xparts of more complex patterns) will benefit most.
  792. XYou may have only one study active at a time\*(--if you study a different
  793. Xscalar the first is \*(L"unstudied\*(R".
  794. X(The way study works is this: a linked list of every character in the string
  795. Xto be searched is made, so we know, for example, where all the \*(L'k\*(R' characters
  796. Xare.
  797. XFrom each search string, the rarest character is selected, based on some
  798. Xstatic frequency tables constructed from some C programs and English text.
  799. XOnly those places that contain this \*(L"rarest\*(R" character are examined.)
  800. X.Sp
  801. XFor example, here is a loop which inserts index producing entries before any line
  802. Xcontaining a certain pattern:
  803. X.nf
  804. X
  805. X.ne 8
  806. X    while (<>) {
  807. X        study;
  808. X        print ".IX foo\en" if /\ebfoo\eb/;
  809. X        print ".IX bar\en" if /\ebbar\eb/;
  810. X        print ".IX blurfl\en" if /\ebblurfl\eb/;
  811. X        .\|.\|.
  812. X        print;
  813. X    }
  814. X
  815. X.fi
  816. XIn searching for /\ebfoo\eb/, only those locations in $_ that contain \*(L'f\*(R'
  817. Xwill be looked at, because \*(L'f\*(R' is rarer than \*(L'o\*(R'.
  818. XIn general, this is a big win except in pathological cases.
  819. XThe only question is whether it saves you more time than it took to build
  820. Xthe linked list in the first place.
  821. X.Sp
  822. XNote that if you have to look for strings that you don't know till runtime,
  823. Xyou can build an entire loop as a string and eval that to avoid recompiling
  824. Xall your patterns all the time.
  825. XTogether with setting $/ to input entire files as one record, this can
  826. Xbe very fast, often faster than specialized programs like fgrep.
  827. XThe following scans a list of files (@files)
  828. Xfor a list of words (@words), and prints out the names of those files that
  829. Xcontain a match:
  830. X.nf
  831. X
  832. X.ne 12
  833. X    $search = \'while (<>) { study;\';
  834. X    foreach $word (@words) {
  835. X        $search .= "++\e$seen{\e$ARGV} if /\eb$word\eb/;\en";
  836. X    }
  837. X    $search .= "}";
  838. X    @ARGV = @files;
  839. X    $/ = "\e177";        # something that doesn't occur
  840. X    eval $search;        # this screams
  841. X    $/ = "\en";        # put back to normal input delim
  842. X    foreach $file (sort keys(%seen)) {
  843. X        print $file, "\en";
  844. X    }
  845. X
  846. X.fi
  847. X.Ip "substr(EXPR,OFFSET,LEN)" 8 2
  848. XExtracts a substring out of EXPR and returns it.
  849. XFirst character is at offset 0, or whatever you've set $[ to.
  850. XIf OFFSET is negative, starts that far from the end of the string.
  851. XYou can use the substr() function as an lvalue, in which case EXPR must
  852. Xbe an lvalue.
  853. XIf you assign something shorter than LEN, the string will shrink, and
  854. Xif you assign something longer than LEN, the string will grow to accomodate it.
  855. XTo keep the string the same length you may need to pad or chop your value using
  856. Xsprintf().
  857. X.Ip "syscall(LIST)" 8 6
  858. X.Ip "syscall LIST" 8
  859. XCalls the system call specified as the first element of the list, passing
  860. Xthe remaining elements as arguments to the system call.
  861. XIf unimplemented, produces a fatal error.
  862. XThe arguments are interpreted as follows: if a given argument is numeric,
  863. Xthe argument is passed as an int.
  864. XIf not, the pointer to the string value is passed.
  865. XYou are responsible to make sure a string is pre-extended long enough
  866. Xto receive any result that might be written into a string.
  867. XIf your integer arguments are not literals and have never been interpreted
  868. Xin a numeric context, you may need to add 0 to them to force them to look
  869. Xlike numbers.
  870. X.nf
  871. X
  872. X    do 'syscall.h';        # may need to run makelib
  873. X    syscall(&SYS_write, fileno(STDOUT), "hi there\en", 9);
  874. X
  875. X.fi
  876. X.Ip "system(LIST)" 8 6
  877. X.Ip "system LIST" 8
  878. XDoes exactly the same thing as \*(L"exec LIST\*(R" except that a fork
  879. Xis done first, and the parent process waits for the child process to complete.
  880. XNote that argument processing varies depending on the number of arguments.
  881. XThe return value is the exit status of the program as returned by the wait()
  882. Xcall.
  883. XTo get the actual exit value divide by 256.
  884. XSee also
  885. X.IR exec .
  886. X.Ip "symlink(OLDFILE,NEWFILE)" 8 2
  887. XCreates a new filename symbolically linked to the old filename.
  888. XReturns 1 for success, 0 otherwise.
  889. XOn systems that don't support symbolic links, produces a fatal error at
  890. Xrun time.
  891. XTo check for that, use eval:
  892. X.nf
  893. X
  894. X    $symlink_exists = (eval \'symlink("","");\', $@ eq \'\');
  895. X
  896. X.fi
  897. X.Ip "tell(FILEHANDLE)" 8 6
  898. X.Ip "tell FILEHANDLE" 8 6
  899. X.Ip "tell" 8
  900. XReturns the current file position for FILEHANDLE.
  901. XFILEHANDLE may be an expression whose value gives the name of the actual
  902. Xfilehandle.
  903. XIf FILEHANDLE is omitted, assumes the file last read.
  904. X.Ip "telldir(DIRHANDLE)" 8 5
  905. X.Ip "telldir DIRHANDLE" 8
  906. XReturns the current position of the readdir() routines on DIRHANDLE.
  907. XValue may be given to seekdir() to access a particular location in
  908. Xa directory.
  909. XHas the same caveats about possible directory compaction as the corresponding
  910. Xsystem library routine.
  911. X.Ip "time" 8 4
  912. XReturns the number of non-leap seconds since January 1, 1970, UTC.
  913. XSuitable for feeding to gmtime() and localtime().
  914. X.Ip "times" 8 4
  915. XReturns a four-element array giving the user and system times, in seconds, for this
  916. Xprocess and the children of this process.
  917. X.Sp
  918. X    ($user,$system,$cuser,$csystem) = times;
  919. X.Sp
  920. X.Ip "tr/SEARCHLIST/REPLACEMENTLIST/" 8 5
  921. X.Ip "y/SEARCHLIST/REPLACEMENTLIST/" 8
  922. XTranslates all occurrences of the characters found in the search list with
  923. Xthe corresponding character in the replacement list.
  924. XIt returns the number of characters replaced.
  925. XIf no string is specified via the =~ or !~ operator,
  926. Xthe $_ string is translated.
  927. X(The string specified with =~ must be a scalar variable, an array element,
  928. Xor an assignment to one of those, i.e. an lvalue.)
  929. XFor
  930. X.I sed
  931. Xdevotees,
  932. X.I y
  933. Xis provided as a synonym for
  934. X.IR tr .
  935. XExamples:
  936. X.nf
  937. X
  938. X    $ARGV[1] \|=~ \|y/A\-Z/a\-z/;    \h'|3i'# canonicalize to lower case
  939. X
  940. X    $cnt = tr/*/*/;        \h'|3i'# count the stars in $_
  941. X
  942. X    ($HOST = $host) =~ tr/a\-z/A\-Z/;
  943. X
  944. X    y/\e001\-@[\-_{\-\e177/ /;    \h'|3i'# change non-alphas to space
  945. X
  946. X.fi
  947. X.Ip "umask(EXPR)" 8 4
  948. X.Ip "umask EXPR" 8
  949. XSets the umask for the process and returns the old one.
  950. XIf EXPR is omitted, merely returns current umask.
  951. X.Ip "undef(EXPR)" 8 6
  952. X.Ip "undef EXPR" 8
  953. X.Ip "undef" 8
  954. XUndefines the value of EXPR, which must be an lvalue.
  955. XUse only on a scalar value, an entire array, or a subroutine name (using &).
  956. X(Undef will probably not do what you expect on most predefined variables or
  957. Xdbm array values.)
  958. XAlways returns the undefined value.
  959. XYou can omit the EXPR, in which case nothing is undefined, but you still
  960. Xget an undefined value that you could, for instance, return from a subroutine.
  961. XExamples:
  962. X.nf
  963. X
  964. X.ne 6
  965. X    undef $foo;
  966. X    undef $bar{'blurfl'};
  967. X    undef @ary;
  968. X    undef %assoc;
  969. X    undef &mysub;
  970. X    return (wantarray ? () : undef) if $they_blew_it;
  971. X
  972. X.fi
  973. X.Ip "unlink(LIST)" 8 4
  974. X.Ip "unlink LIST" 8
  975. XDeletes a list of files.
  976. XReturns the number of files successfully deleted.
  977. X.nf
  978. X
  979. X.ne 2
  980. X    $cnt = unlink \'a\', \'b\', \'c\';
  981. X    unlink @goners;
  982. X    unlink <*.bak>;
  983. X
  984. X.fi
  985. XNote: unlink will not delete directories unless you are superuser and the
  986. X.B \-U
  987. Xflag is supplied to
  988. X.IR perl .
  989. XEven if these conditions are met, be warned that unlinking a directory
  990. Xcan inflict damage on your filesystem.
  991. XUse rmdir instead.
  992. X.Ip "unpack(TEMPLATE,EXPR)" 8 4
  993. XUnpack does the reverse of pack: it takes a string representing
  994. Xa structure and expands it out into an array value, returning the array
  995. Xvalue.
  996. XThe TEMPLATE has the same format as in the pack function.
  997. XHere's a subroutine that does substring:
  998. X.nf
  999. X
  1000. X.ne 4
  1001. X    sub substr {
  1002. X        local($what,$where,$howmuch) = @_;
  1003. X        unpack("x$where a$howmuch", $what);
  1004. X    }
  1005. X
  1006. X.ne 3
  1007. Xand then there's
  1008. X
  1009. X    sub ord { unpack("c",$_[0]); }
  1010. X
  1011. X.fi
  1012. X.Ip "unshift(ARRAY,LIST)" 8 4
  1013. XDoes the opposite of a
  1014. X.IR shift .
  1015. XOr the opposite of a
  1016. X.IR push ,
  1017. Xdepending on how you look at it.
  1018. XPrepends list to the front of the array, and returns the number of elements
  1019. Xin the new array.
  1020. X.nf
  1021. X
  1022. X    unshift(ARGV, \'\-e\') unless $ARGV[0] =~ /^\-/;
  1023. X
  1024. X.fi
  1025. X.Ip "utime(LIST)" 8 2
  1026. X.Ip "utime LIST" 8 2
  1027. XChanges the access and modification times on each file of a list of files.
  1028. XThe first two elements of the list must be the NUMERICAL access and
  1029. Xmodification times, in that order.
  1030. XReturns the number of files successfully changed.
  1031. XThe inode modification time of each file is set to the current time.
  1032. XExample of a \*(L"touch\*(R" command:
  1033. X.nf
  1034. X
  1035. X.ne 3
  1036. X    #!/usr/bin/perl
  1037. X    $now = time;
  1038. X    utime $now, $now, @ARGV;
  1039. X
  1040. X.fi
  1041. X.Ip "values(ASSOC_ARRAY)" 8 6
  1042. X.Ip "values ASSOC_ARRAY" 8
  1043. XReturns a normal array consisting of all the values of the named associative
  1044. Xarray.
  1045. XThe values are returned in an apparently random order, but it is the same order
  1046. Xas either the keys() or each() function would produce on the same array.
  1047. XSee also keys() and each().
  1048. X.Ip "vec(EXPR,OFFSET,BITS)" 8 2
  1049. XTreats a string as a vector of unsigned integers, and returns the value
  1050. Xof the bitfield specified.
  1051. XMay also be assigned to.
  1052. XBITS must be a power of two from 1 to 32.
  1053. X.Sp
  1054. XVectors created with vec() can also be manipulated with the logical operators
  1055. X|, & and ^,
  1056. Xwhich will assume a bit vector operation is desired when both operands are
  1057. Xstrings.
  1058. XThis interpretation is not enabled unless there is at least one vec() in
  1059. Xyour program, to protect older programs.
  1060. X.Ip "wait" 8 6
  1061. XWaits for a child process to terminate and returns the pid of the deceased
  1062. Xprocess.
  1063. XThe status is returned in $?.
  1064. X.Ip "wantarray" 8 4
  1065. XReturns true if the context of the currently executing subroutine
  1066. Xis looking for an array value.
  1067. XReturns false if the context is looking for a scalar.
  1068. X.nf
  1069. X
  1070. X    return wantarray ? () : undef;
  1071. X
  1072. X.fi
  1073. X.Ip "warn(LIST)" 8 4
  1074. X.Ip "warn LIST" 8
  1075. XProduces a message on STDERR just like \*(L"die\*(R", but doesn't exit.
  1076. X.Ip "write(FILEHANDLE)" 8 6
  1077. X.Ip "write(EXPR)" 8
  1078. X.Ip "write(\|)" 8
  1079. XWrites a formatted record (possibly multi-line) to the specified file,
  1080. Xusing the format associated with that file.
  1081. XBy default the format for a file is the one having the same name is the
  1082. Xfilehandle, but the format for the current output channel (see
  1083. X.IR select )
  1084. Xmay be set explicitly
  1085. Xby assigning the name of the format to the $~ variable.
  1086. X.Sp
  1087. XTop of form processing is handled automatically:
  1088. Xif there is insufficient room on the current page for the formatted 
  1089. Xrecord, the page is advanced, a special top-of-page format is used
  1090. Xto format the new page header, and then the record is written.
  1091. XBy default the top-of-page format is \*(L"top\*(R", but it
  1092. Xmay be set to the
  1093. Xformat of your choice by assigning the name to the $^ variable.
  1094. X.Sp
  1095. XIf FILEHANDLE is unspecified, output goes to the current default output channel,
  1096. Xwhich starts out as
  1097. X.I STDOUT
  1098. Xbut may be changed by the
  1099. X.I select
  1100. Xoperator.
  1101. XIf the FILEHANDLE is an EXPR, then the expression is evaluated and the
  1102. Xresulting string is used to look up the name of the FILEHANDLE at run time.
  1103. XFor more on formats, see the section on formats later on.
  1104. X.Sp
  1105. XNote that write is NOT the opposite of read.
  1106. !STUFFY!FUNK!
  1107. echo Extracting perl.h
  1108. sed >perl.h <<'!STUFFY!FUNK!' -e 's/X//'
  1109. X/* $Header: perl.h,v 3.0 89/10/18 15:21:21 lwall Locked $
  1110. X *
  1111. X *    Copyright (c) 1989, Larry Wall
  1112. X *
  1113. X *    You may distribute under the terms of the GNU General Public License
  1114. X *    as specified in the README file that comes with the perl 3.0 kit.
  1115. X *
  1116. X * $Log:    perl.h,v $
  1117. X * Revision 3.0  89/10/18  15:21:21  lwall
  1118. X * 3.0 baseline
  1119. X * 
  1120. X */
  1121. X
  1122. X#ifndef lint
  1123. X#define DEBUGGING
  1124. X#endif
  1125. X
  1126. X#define VOIDUSED 1
  1127. X#include "config.h"
  1128. X
  1129. X#ifdef IAMSUID
  1130. X#   ifndef TAINT
  1131. X#    define TAINT
  1132. X#   endif
  1133. X#endif
  1134. X
  1135. X#ifdef MEMCPY
  1136. Xextern char *memcpy(), *memset();
  1137. X#define bcopy(s1,s2,l) memcpy(s2,s1,l)
  1138. X#define bzero(s,l) memset(s,0,l)
  1139. X#endif
  1140. X#ifndef BCMP        /* prefer bcmp slightly 'cuz it doesn't order */
  1141. X#define bcmp(s1,s2,l) memcmp(s1,s2,l)
  1142. X#endif
  1143. X
  1144. X#include <stdio.h>
  1145. X#include <ctype.h>
  1146. X#include <setjmp.h>
  1147. X#include <sys/param.h>    /* if this needs types.h we're still wrong */
  1148. X
  1149. X#ifndef _TYPES_        /* If types.h defines this it's easy. */
  1150. X#ifndef major        /* Does everyone's types.h define this? */
  1151. X#include <sys/types.h>
  1152. X#endif
  1153. X#endif
  1154. X
  1155. X#include <sys/stat.h>
  1156. X
  1157. X#ifdef TMINSYS
  1158. X#include <sys/time.h>
  1159. X#else
  1160. X#ifdef I_SYSTIME
  1161. X#include <sys/time.h>
  1162. X#else
  1163. X#include <time.h>
  1164. X#endif
  1165. X#endif
  1166. X
  1167. X#include <sys/times.h>
  1168. X
  1169. X#ifdef I_SYSIOCTL
  1170. X#ifndef _IOCTL_
  1171. X#include <sys/ioctl.h>
  1172. X#endif
  1173. X#endif
  1174. X
  1175. X#if defined(mc300) || defined(mc500) || defined(mc700)    /* MASSCOMP */
  1176. X#ifdef SOCKETPAIR
  1177. X#undef SOCKETPAIR
  1178. X#endif
  1179. X#ifdef NDBM
  1180. X#undef NDBM
  1181. X#endif
  1182. X#endif
  1183. X
  1184. X#ifdef NDBM
  1185. X#include <ndbm.h>
  1186. X#define SOME_DBM
  1187. X#else
  1188. X#ifdef ODBM
  1189. X#ifdef NULL
  1190. X#undef NULL        /* suppress redefinition message */
  1191. X#endif
  1192. X#include <dbm.h>
  1193. X#ifdef NULL
  1194. X#undef NULL
  1195. X#endif
  1196. X#define NULL 0        /* silly thing is, we don't even use this */
  1197. X#define SOME_DBM
  1198. X#define dbm_fetch(db,dkey) fetch(dkey)
  1199. X#define dbm_delete(db,dkey) delete(dkey)
  1200. X#define dbm_store(db,dkey,dcontent,flags) store(dkey,dcontent)
  1201. X#define dbm_close(db) dbmclose()
  1202. X#define dbm_firstkey(db) firstkey()
  1203. X#endif /* ODBM */
  1204. X#endif /* NDBM */
  1205. X#ifdef SOME_DBM
  1206. XEXT char *dbmkey;
  1207. XEXT int dbmlen;
  1208. X#endif
  1209. X
  1210. X#if INTSIZE == 2
  1211. X#define htoni htons
  1212. X#define ntohi ntohs
  1213. X#else
  1214. X#define htoni htonl
  1215. X#define ntohi ntohl
  1216. X#endif
  1217. X
  1218. X#ifdef I_DIRENT
  1219. X#include <dirent.h>
  1220. X#define DIRENT dirent
  1221. X#else
  1222. X#ifdef I_SYSDIR
  1223. X#include <sys/dir.h>
  1224. X#define DIRENT direct
  1225. X#endif
  1226. X#endif
  1227. X
  1228. Xtypedef struct arg ARG;
  1229. Xtypedef struct cmd CMD;
  1230. Xtypedef struct formcmd FCMD;
  1231. Xtypedef struct scanpat SPAT;
  1232. Xtypedef struct stio STIO;
  1233. Xtypedef struct sub SUBR;
  1234. Xtypedef struct string STR;
  1235. Xtypedef struct atbl ARRAY;
  1236. Xtypedef struct htbl HASH;
  1237. Xtypedef struct regexp REGEXP;
  1238. Xtypedef struct stabptrs STBP;
  1239. Xtypedef struct stab STAB;
  1240. X
  1241. X#include "handy.h"
  1242. X#include "regexp.h"
  1243. X#include "str.h"
  1244. X#include "util.h"
  1245. X#include "form.h"
  1246. X#include "stab.h"
  1247. X#include "spat.h"
  1248. X#include "arg.h"
  1249. X#include "cmd.h"
  1250. X#include "array.h"
  1251. X#include "hash.h"
  1252. X
  1253. X#if defined(iAPX286) || defined(M_I286) || defined(I80286)
  1254. X#   define I286
  1255. X#endif
  1256. X
  1257. X#ifndef    __STDC__
  1258. X#ifdef CHARSPRINTF
  1259. X    char *sprintf();
  1260. X#else
  1261. X    int sprintf();
  1262. X#endif
  1263. X#endif
  1264. X
  1265. XEXT char *Yes INIT("1");
  1266. XEXT char *No INIT("");
  1267. X
  1268. X/* "gimme" values */
  1269. X
  1270. X/* Note: cmd.c assumes that it can use && to produce one of these values! */
  1271. X#define G_SCALAR 0
  1272. X#define G_ARRAY 1
  1273. X
  1274. X#ifdef CRIPPLED_CC
  1275. Xint str_true();
  1276. X#else /* !CRIPPLED_CC */
  1277. X#define str_true(str) (Str = (str), \
  1278. X    (Str->str_pok ? \
  1279. X        ((*Str->str_ptr > '0' || \
  1280. X          Str->str_cur > 1 || \
  1281. X          (Str->str_cur && *Str->str_ptr != '0')) ? 1 : 0) \
  1282. X    : \
  1283. X        (Str->str_nok ? (Str->str_u.str_nval != 0.0) : 0 ) ))
  1284. X#endif /* CRIPPLED_CC */
  1285. X
  1286. X#ifdef DEBUGGING
  1287. X#define str_peek(str) (Str = (str), \
  1288. X    (Str->str_pok ? \
  1289. X        Str->str_ptr : \
  1290. X        (Str->str_nok ? \
  1291. X        (sprintf(tokenbuf,"num(%g)",Str->str_u.str_nval), \
  1292. X            (char*)tokenbuf) : \
  1293. X        "" )))
  1294. X#endif
  1295. X
  1296. X#ifdef CRIPPLED_CC
  1297. Xchar *str_get();
  1298. X#else
  1299. X#ifdef TAINT
  1300. X#define str_get(str) (Str = (str), tainted |= Str->str_tainted, \
  1301. X    (Str->str_pok ? Str->str_ptr : str_2ptr(Str)))
  1302. X#else
  1303. X#define str_get(str) (Str = (str), (Str->str_pok ? Str->str_ptr : str_2ptr(Str)))
  1304. X#endif /* TAINT */
  1305. X#endif /* CRIPPLED_CC */
  1306. X
  1307. X#ifdef CRIPPLED_CC
  1308. Xdouble str_gnum();
  1309. X#else /* !CRIPPLED_CC */
  1310. X#ifdef TAINT
  1311. X#define str_gnum(str) (Str = (str), tainted |= Str->str_tainted, \
  1312. X    (Str->str_nok ? Str->str_u.str_nval : str_2num(Str)))
  1313. X#else /* !TAINT */
  1314. X#define str_gnum(str) (Str = (str), (Str->str_nok ? Str->str_u.str_nval : str_2num(Str)))
  1315. X#endif /* TAINT*/
  1316. X#endif /* CRIPPLED_CC */
  1317. XEXT STR *Str;
  1318. X
  1319. X#define GROWSTR(pp,lp,len) if (*(lp) < (len)) growstr(pp,lp,len)
  1320. X
  1321. X#define STR_GROW(str,len) if ((str)->str_len < (len)) str_grow(str,len)
  1322. X
  1323. X#ifndef BYTEORDER
  1324. X#define BYTEORDER 01234
  1325. X#endif
  1326. X
  1327. X#ifndef HTONL
  1328. X#if BYTEORDER != 04321
  1329. X#define HTONS
  1330. X#define HTONL
  1331. X#define NTOHS
  1332. X#define NTOHL
  1333. X#define MYSWAP
  1334. X#define htons my_swap
  1335. X#define htonl my_htonl
  1336. X#define ntohs my_swap
  1337. X#define ntohl my_ntohl
  1338. X#endif
  1339. X#else
  1340. X#if BYTEORDER == 04321
  1341. X#undef HTONS
  1342. X#undef HTONL
  1343. X#undef NTOHS
  1344. X#undef NTOHL
  1345. X#endif
  1346. X#endif
  1347. X
  1348. XCMD *add_label();
  1349. XCMD *block_head();
  1350. XCMD *append_line();
  1351. XCMD *make_acmd();
  1352. XCMD *make_ccmd();
  1353. XCMD *make_icmd();
  1354. XCMD *invert();
  1355. XCMD *addcond();
  1356. XCMD *addloop();
  1357. XCMD *wopt();
  1358. XCMD *over();
  1359. X
  1360. XSTAB *stabent();
  1361. XSTAB *genstab();
  1362. X
  1363. XARG *stab2arg();
  1364. XARG *op_new();
  1365. XARG *make_op();
  1366. XARG *make_match();
  1367. XARG *make_split();
  1368. XARG *rcatmaybe();
  1369. XARG *listish();
  1370. XARG *maybelistish();
  1371. XARG *localize();
  1372. XARG *fixeval();
  1373. XARG *jmaybe();
  1374. XARG *l();
  1375. XARG *fixl();
  1376. XARG *mod_match();
  1377. XARG *make_list();
  1378. XARG *cmd_to_arg();
  1379. XARG *addflags();
  1380. XARG *hide_ary();
  1381. XARG *cval_to_arg();
  1382. X
  1383. XSTR *str_new();
  1384. XSTR *stab_str();
  1385. X
  1386. Xint do_each();
  1387. Xint do_subr();
  1388. Xint do_match();
  1389. Xint do_unpack();
  1390. Xint eval();        /* this evaluates expressions */
  1391. Xint do_eval();        /* this evaluates eval operator */
  1392. Xint do_assign();
  1393. X
  1394. XSUBR *make_sub();
  1395. X
  1396. XFCMD *load_format();
  1397. X
  1398. Xchar *scanpat();
  1399. Xchar *scansubst();
  1400. Xchar *scantrans();
  1401. Xchar *scanstr();
  1402. Xchar *scanreg();
  1403. Xchar *str_append_till();
  1404. Xchar *str_gets();
  1405. Xchar *str_grow();
  1406. X
  1407. Xbool do_open();
  1408. Xbool do_close();
  1409. Xbool do_print();
  1410. Xbool do_aprint();
  1411. Xbool do_exec();
  1412. Xbool do_aexec();
  1413. X
  1414. Xint do_subst();
  1415. Xint cando();
  1416. Xint ingroup();
  1417. X
  1418. Xvoid str_replace();
  1419. Xvoid str_inc();
  1420. Xvoid str_dec();
  1421. Xvoid str_free();
  1422. Xvoid stab_clear();
  1423. Xvoid do_join();
  1424. Xvoid do_sprintf();
  1425. Xvoid do_accept();
  1426. Xvoid do_vecset();
  1427. Xvoid savelist();
  1428. Xvoid saveitem();
  1429. Xvoid saveint();
  1430. Xvoid savelong();
  1431. Xvoid savesptr();
  1432. Xvoid savehptr();
  1433. Xvoid restorelist();
  1434. XHASH *savehash();
  1435. XARRAY *saveary();
  1436. X
  1437. XEXT line_t line INIT(0);
  1438. XEXT line_t subline INIT(0);
  1439. XEXT STR *subname INIT(Nullstr);
  1440. XEXT int arybase INIT(0);
  1441. X
  1442. Xstruct outrec {
  1443. X    line_t  o_lines;
  1444. X    char    *o_str;
  1445. X    int     o_len;
  1446. X};
  1447. X
  1448. XEXT struct outrec outrec;
  1449. XEXT struct outrec toprec;
  1450. X
  1451. XEXT STAB *stdinstab INIT(Nullstab);
  1452. XEXT STAB *last_in_stab INIT(Nullstab);
  1453. XEXT STAB *defstab INIT(Nullstab);
  1454. XEXT STAB *argvstab INIT(Nullstab);
  1455. XEXT STAB *envstab INIT(Nullstab);
  1456. XEXT STAB *sigstab INIT(Nullstab);
  1457. XEXT STAB *defoutstab INIT(Nullstab);
  1458. XEXT STAB *curoutstab INIT(Nullstab);
  1459. XEXT STAB *argvoutstab INIT(Nullstab);
  1460. XEXT STAB *incstab INIT(Nullstab);
  1461. XEXT STAB *leftstab INIT(Nullstab);
  1462. XEXT STAB *amperstab INIT(Nullstab);
  1463. XEXT STAB *rightstab INIT(Nullstab);
  1464. XEXT STAB *DBstab INIT(Nullstab);
  1465. XEXT STAB *DBsub INIT(Nullstab);
  1466. X
  1467. XEXT HASH *defstash;        /* main symbol table */
  1468. XEXT HASH *curstash;        /* symbol table for current package */
  1469. XEXT HASH *debstash;        /* symbol table for perldb package */
  1470. X
  1471. XEXT STR *curstname;        /* name of current package */
  1472. X
  1473. XEXT STR *freestrroot INIT(Nullstr);
  1474. XEXT STR *lastretstr INIT(Nullstr);
  1475. XEXT STR *DBsingle INIT(Nullstr);
  1476. X
  1477. XEXT int lastspbase;
  1478. XEXT int lastsize;
  1479. X
  1480. XEXT char *filename;
  1481. XEXT char *origfilename;
  1482. XEXT FILE *rsfp;
  1483. XEXT char buf[1024];
  1484. XEXT char *bufptr;
  1485. XEXT char *oldbufptr;
  1486. XEXT char *oldoldbufptr;
  1487. XEXT char *bufend;
  1488. X
  1489. XEXT STR *linestr INIT(Nullstr);
  1490. X
  1491. XEXT char record_separator INIT('\n');
  1492. XEXT int rslen INIT(1);
  1493. XEXT char *ofs INIT(Nullch);
  1494. XEXT int ofslen INIT(0);
  1495. XEXT char *ors INIT(Nullch);
  1496. XEXT int orslen INIT(0);
  1497. XEXT char *ofmt INIT(Nullch);
  1498. XEXT char *inplace INIT(Nullch);
  1499. XEXT char *nointrp INIT("");
  1500. X
  1501. XEXT bool preprocess INIT(FALSE);
  1502. XEXT bool minus_n INIT(FALSE);
  1503. XEXT bool minus_p INIT(FALSE);
  1504. XEXT bool minus_a INIT(FALSE);
  1505. XEXT bool doswitches INIT(FALSE);
  1506. XEXT bool dowarn INIT(FALSE);
  1507. XEXT bool allstabs INIT(FALSE);    /* init all customary symbols in symbol table?*/
  1508. XEXT bool sawampersand INIT(FALSE);    /* must save all match strings */
  1509. XEXT bool sawstudy INIT(FALSE);        /* do fbminstr on all strings */
  1510. XEXT bool sawi INIT(FALSE);        /* study must assume case insensitive */
  1511. XEXT bool sawvec INIT(FALSE);
  1512. X
  1513. XEXT int csh INIT(0);        /* 1 if /bin/csh is there, -1 if not */
  1514. X
  1515. X#ifdef TAINT
  1516. XEXT bool tainted INIT(FALSE);        /* using variables controlled by $< */
  1517. X#endif
  1518. X
  1519. X#define TMPPATH "/tmp/perl-eXXXXXX"
  1520. XEXT char *e_tmpname;
  1521. XEXT FILE *e_fp INIT(Nullfp);
  1522. X
  1523. XEXT char tokenbuf[256];
  1524. XEXT int expectterm INIT(TRUE);        /* how to interpret ambiguous tokens */
  1525. XEXT int in_eval INIT(FALSE);        /* trap fatal errors? */
  1526. XEXT int multiline INIT(0);        /* $*--do strings hold >1 line? */
  1527. XEXT int forkprocess;            /* so do_open |- can return proc# */
  1528. XEXT int do_undump INIT(0);        /* -u or dump seen? */
  1529. XEXT int error_count INIT(0);        /* how many errors so far, max 10 */
  1530. XEXT int multi_start INIT(0);        /* 1st line of multi-line string */
  1531. XEXT int multi_end INIT(0);        /* last line of multi-line string */
  1532. XEXT int multi_open INIT(0);        /* delimiter of said string */
  1533. XEXT int multi_close INIT(0);        /* delimiter of said string */
  1534. X
  1535. XFILE *popen();
  1536. X/* char *str_get(); */
  1537. XSTR *interp();
  1538. Xvoid free_arg();
  1539. XSTIO *stio_new();
  1540. X
  1541. XEXT struct stat statbuf;
  1542. XEXT struct stat statcache;
  1543. XSTAB *statstab INIT(Nullstab);
  1544. XSTR *statname;
  1545. XEXT struct tms timesbuf;
  1546. XEXT int uid;
  1547. XEXT int euid;
  1548. XEXT int gid;
  1549. XEXT int egid;
  1550. XUIDTYPE getuid();
  1551. XUIDTYPE geteuid();
  1552. XGIDTYPE getgid();
  1553. XGIDTYPE getegid();
  1554. XEXT int unsafe;
  1555. X
  1556. X#ifdef DEBUGGING
  1557. XEXT int debug INIT(0);
  1558. XEXT int dlevel INIT(0);
  1559. XEXT int dlmax INIT(128);
  1560. XEXT char *debname;
  1561. XEXT char *debdelim;
  1562. X#define YYDEBUG 1
  1563. Xextern int yydebug;
  1564. X#endif
  1565. XEXT int perldb INIT(0);
  1566. X
  1567. XEXT line_t cmdline INIT(NOLINE);
  1568. X
  1569. XEXT STR str_undef;
  1570. XEXT STR str_no;
  1571. XEXT STR str_yes;
  1572. X
  1573. X/* runtime control stuff */
  1574. X
  1575. XEXT struct loop {
  1576. X    char *loop_label;        /* what the loop was called, if anything */
  1577. X    int loop_sp;        /* stack pointer to copy stuff down to */
  1578. X    jmp_buf loop_env;
  1579. X} *loop_stack;
  1580. X
  1581. XEXT int loop_ptr INIT(-1);
  1582. XEXT int loop_max INIT(128);
  1583. X
  1584. XEXT jmp_buf top_env;
  1585. XEXT jmp_buf eval_env;
  1586. X
  1587. XEXT char *goto_targ INIT(Nullch);    /* cmd_exec gets strange when set */
  1588. X
  1589. XEXT ARRAY *stack;        /* THE STACK */
  1590. X
  1591. XEXT ARRAY *savestack;        /* to save non-local values on */
  1592. X
  1593. XEXT ARRAY *tosave;        /* strings to save on recursive subroutine */
  1594. X
  1595. XEXT ARRAY *lineary;        /* lines of script for debugger */
  1596. X
  1597. XEXT ARRAY *pidstatary;        /* keep pids and statuses by fd for mypopen */
  1598. X
  1599. Xdouble atof();
  1600. Xlong time();
  1601. Xstruct tm *gmtime(), *localtime();
  1602. Xchar *mktemp();
  1603. Xchar *index(), *rindex();
  1604. Xchar *strcpy(), *strcat();
  1605. X
  1606. X#ifdef EUNICE
  1607. X#define UNLINK unlnk
  1608. Xint unlnk();
  1609. X#else
  1610. X#define UNLINK unlink
  1611. X#endif
  1612. X
  1613. X#ifndef SETREUID
  1614. X#ifdef SETRESUID
  1615. X#define setreuid(r,e) setresuid(r,e,-1)
  1616. X#define SETREUID
  1617. X#endif
  1618. X#endif
  1619. X#ifndef SETREGID
  1620. X#ifdef SETRESGID
  1621. X#define setregid(r,e) setresgid(r,e,-1)
  1622. X#define SETREGID
  1623. X#endif
  1624. X#endif
  1625. !STUFFY!FUNK!
  1626. echo Extracting t/op.sleep
  1627. sed >t/op.sleep <<'!STUFFY!FUNK!' -e 's/X//'
  1628. X#!./perl
  1629. X
  1630. X# $Header: op.sleep,v 3.0 89/10/18 15:31:15 lwall Locked $
  1631. X
  1632. Xprint "1..1\n";
  1633. X
  1634. X$x = sleep 2;
  1635. Xif ($x == 2) {print "ok 1\n";} else {print "not ok 1\n";}
  1636. !STUFFY!FUNK!
  1637. echo ""
  1638. echo "End of kit 8 (of 24)"
  1639. cat /dev/null >kit8isdone
  1640. run=''
  1641. config=''
  1642. 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; do
  1643.     if test -f kit${iskit}isdone; then
  1644.     run="$run $iskit"
  1645.     else
  1646.     todo="$todo $iskit"
  1647.     fi
  1648. done
  1649. case $todo in
  1650.     '')
  1651.     echo "You have run all your kits.  Please read README and then type Configure."
  1652.     chmod 755 Configure
  1653.     ;;
  1654.     *)  echo "You have run$run."
  1655.     echo "You still need to run$todo."
  1656.     ;;
  1657. esac
  1658. : Someone might mail this, so... dowic cxp