home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume15 / perl2 / part05 < prev    next >
Encoding:
Internet Message Format  |  1989-01-05  |  48.6 KB

  1. Subject:  v15i094:  Perl, release 2, Part05/15
  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 15, Issue 94
  8. Archive-name: perl2/part05
  9.  
  10. #! /bin/sh
  11.  
  12. # Make a new directory for the perl sources, cd to it, and run kits 1
  13. # thru 15 through sh.  When all 15 kits have been run, read README.
  14.  
  15. echo "This is perl 2.0 kit 5 (of 15).  If kit 5 is complete, the line"
  16. echo '"'"End of kit 5 (of 15)"'" 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.1
  21. sed >perl.man.1 <<'!STUFFY!FUNK!' -e 's/X//'
  22. X.rn '' }`
  23. X''' $Header: perl.man.1,v 2.0 88/06/05 00:09:23 root Exp $
  24. X''' 
  25. X''' $Log:    perl.man.1,v $
  26. X''' Revision 2.0  88/06/05  00:09:23  root
  27. X''' Baseline version 2.0.
  28. X''' 
  29. X''' 
  30. X.de Sh
  31. X.br
  32. X.ne 5
  33. X.PP
  34. X\fB\\$1\fR
  35. X.PP
  36. X..
  37. X.de Sp
  38. X.if t .sp .5v
  39. X.if n .sp
  40. X..
  41. X.de Ip
  42. X.br
  43. X.ie \\n.$>=3 .ne \\$3
  44. X.el .ne 3
  45. X.IP "\\$1" \\$2
  46. X..
  47. X'''
  48. X'''     Set up \*(-- to give an unbreakable dash;
  49. X'''     string Tr holds user defined translation string.
  50. X'''     Bell System Logo is used as a dummy character.
  51. X'''
  52. X.tr \(*W-|\(bv\*(Tr
  53. X.ie n \{\
  54. X.ds -- \(*W-
  55. X.if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
  56. X.if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
  57. X.ds L" ""
  58. X.ds R" ""
  59. X.ds L' '
  60. X.ds R' '
  61. X'br\}
  62. X.el\{\
  63. X.ds -- \(em\|
  64. X.tr \*(Tr
  65. X.ds L" ``
  66. X.ds R" ''
  67. X.ds L' `
  68. X.ds R' '
  69. X'br\}
  70. X.TH PERL 1 LOCAL
  71. X.SH NAME
  72. Xperl - Practical Extraction and Report Language
  73. X.SH SYNOPSIS
  74. X.B perl [options] filename args
  75. X.SH DESCRIPTION
  76. X.I Perl
  77. Xis a interpreted language optimized for scanning arbitrary text files,
  78. Xextracting information from those text files, and printing reports based
  79. Xon that information.
  80. XIt's also a good language for many system management tasks.
  81. XThe language is intended to be practical (easy to use, efficient, complete)
  82. Xrather than beautiful (tiny, elegant, minimal).
  83. XIt combines (in the author's opinion, anyway) some of the best features of C,
  84. X\fIsed\fR, \fIawk\fR, and \fIsh\fR,
  85. Xso people familiar with those languages should have little difficulty with it.
  86. X(Language historians will also note some vestiges of \fIcsh\fR, Pascal, and
  87. Xeven BASIC-PLUS.)
  88. XExpression syntax corresponds quite closely to C expression syntax.
  89. XIf you have a problem that would ordinarily use \fIsed\fR
  90. Xor \fIawk\fR or \fIsh\fR, but it
  91. Xexceeds their capabilities or must run a little faster,
  92. Xand you don't want to write the silly thing in C, then
  93. X.I perl
  94. Xmay be for you.
  95. XThere are also translators to turn your sed and awk scripts into perl scripts.
  96. XOK, enough hype.
  97. X.PP
  98. XUpon startup,
  99. X.I perl
  100. Xlooks for your script in one of the following places:
  101. X.Ip 1. 4 2
  102. XSpecified line by line via
  103. X.B \-e
  104. Xswitches on the command line.
  105. X.Ip 2. 4 2
  106. XContained in the file specified by the first filename on the command line.
  107. X(Note that systems supporting the #! notation invoke interpreters this way.)
  108. X.Ip 3. 4 2
  109. XPassed in implicity via standard input.
  110. XThis only works if there are no filename arguments\*(--to pass
  111. Xarguments to a stdin script you must explicitly specify a - for the script name.
  112. X.PP
  113. XAfter locating your script,
  114. X.I perl
  115. Xcompiles it to an internal form.
  116. XIf the script is syntactically correct, it is executed.
  117. X.Sh "Options"
  118. XNote: on first reading this section may not make much sense to you.  It's here
  119. Xat the front for easy reference.
  120. X.PP
  121. XA single-character option may be combined with the following option, if any.
  122. XThis is particularly useful when invoking a script using the #! construct which
  123. Xonly allows one argument.  Example:
  124. X.nf
  125. X
  126. X.ne 2
  127. X    #!/usr/bin/perl -spi.bak    # same as -s -p -i.bak
  128. X    .\|.\|.
  129. X
  130. X.fi
  131. XOptions include:
  132. X.TP 5
  133. X.B \-a
  134. Xturns on autosplit mode when used with a \-n or \-p.
  135. XAn implicit split command to the @F array
  136. Xis done as the first thing inside the implicit while loop produced by
  137. Xthe \-n or \-p.
  138. X.nf
  139. X
  140. X    perl -ane 'print pop(@F),"\en";'
  141. X
  142. Xis equivalent to
  143. X
  144. X    while (<>) {
  145. X        @F = split(' ');
  146. X        print pop(@F),"\en";
  147. X    }
  148. X
  149. X.fi
  150. X.TP 5
  151. X.B \-D<number>
  152. Xsets debugging flags.
  153. XTo watch how it executes your script, use
  154. X.B \-D14.
  155. X(This only works if debugging is compiled into your
  156. X.IR perl .)
  157. X.TP 5
  158. X.B \-e commandline
  159. Xmay be used to enter one line of script.
  160. XMultiple
  161. X.B \-e
  162. Xcommands may be given to build up a multi-line script.
  163. XIf
  164. X.B \-e
  165. Xis given,
  166. X.I perl
  167. Xwill not look for a script filename in the argument list.
  168. X.TP 5
  169. X.B \-i<extension>
  170. Xspecifies that files processed by the <> construct are to be edited
  171. Xin-place.
  172. XIt does this by renaming the input file, opening the output file by the
  173. Xsame name, and selecting that output file as the default for print statements.
  174. XThe extension, if supplied, is added to the name of the
  175. Xold file to make a backup copy.
  176. XIf no extension is supplied, no backup is made.
  177. XSaying \*(L"perl -p -i.bak -e "s/foo/bar/;" .\|.\|. \*(R" is the same as using
  178. Xthe script:
  179. X.nf
  180. X
  181. X.ne 2
  182. X    #!/usr/bin/perl -pi.bak
  183. X    s/foo/bar/;
  184. X
  185. Xwhich is equivalent to
  186. X
  187. X.ne 14
  188. X    #!/usr/bin/perl
  189. X    while (<>) {
  190. X        if ($ARGV ne $oldargv) {
  191. X            rename($ARGV,$ARGV . '.bak');
  192. X            open(ARGVOUT,">$ARGV");
  193. X            select(ARGVOUT);
  194. X            $oldargv = $ARGV;
  195. X        }
  196. X        s/foo/bar/;
  197. X    }
  198. X    continue {
  199. X        print;    # this prints to original filename
  200. X    }
  201. X    select(stdout);
  202. X
  203. X.fi
  204. Xexcept that the \-i form doesn't need to compare $ARGV to $oldargv to know when
  205. Xthe filename has changed.
  206. XIt does, however, use ARGVOUT for the selected filehandle.
  207. XNote that stdout is restored as the default output filehandle after the loop.
  208. X.Sp
  209. XYou can use eof to locate the end of each input file, in case you want
  210. Xto append to each file, or reset line numbering (see example under eof).
  211. X.TP 5
  212. X.B \-I<directory>
  213. Xmay be used in conjunction with
  214. X.B \-P
  215. Xto tell the C preprocessor where to look for include files.
  216. XBy default /usr/include and /usr/lib/perl are searched.
  217. X.TP 5
  218. X.B \-n
  219. Xcauses
  220. X.I perl
  221. Xto assume the following loop around your script, which makes it iterate
  222. Xover filename arguments somewhat like \*(L"sed -n\*(R" or \fIawk\fR:
  223. X.nf
  224. X
  225. X.ne 3
  226. X    while (<>) {
  227. X        .\|.\|.        # your script goes here
  228. X    }
  229. X
  230. X.fi
  231. XNote that the lines are not printed by default.
  232. XSee
  233. X.B \-p
  234. Xto have lines printed.
  235. XHere is an efficient way to delete all files older than a week:
  236. X.nf
  237. X
  238. X    find . -mtime +7 -print | perl -ne 'chop;unlink;'
  239. X
  240. X.fi
  241. XThis is faster than using the -exec switch find because you don't have to
  242. Xstart a process on every filename found.
  243. X.TP 5
  244. X.B \-p
  245. Xcauses
  246. X.I perl
  247. Xto assume the following loop around your script, which makes it iterate
  248. Xover filename arguments somewhat like \fIsed\fR:
  249. X.nf
  250. X
  251. X.ne 5
  252. X    while (<>) {
  253. X        .\|.\|.        # your script goes here
  254. X    } continue {
  255. X        print;
  256. X    }
  257. X
  258. X.fi
  259. XNote that the lines are printed automatically.
  260. XTo suppress printing use the
  261. X.B \-n
  262. Xswitch.
  263. XA
  264. X.B \-p
  265. Xoverrides a
  266. X.B \-n
  267. Xswitch.
  268. X.TP 5
  269. X.B \-P
  270. Xcauses your script to be run through the C preprocessor before
  271. Xcompilation by
  272. X.I perl.
  273. X(Since both comments and cpp directives begin with the # character,
  274. Xyou should avoid starting comments with any words recognized
  275. Xby the C preprocessor such as \*(L"if\*(R", \*(L"else\*(R" or \*(L"define\*(R".)
  276. X.TP 5
  277. X.B \-s
  278. Xenables some rudimentary switch parsing for switches on the command line
  279. Xafter the script name but before any filename arguments (or before a --).
  280. XAny switch found there is removed from @ARGV and sets the corresponding variable in the
  281. X.I perl
  282. Xscript.
  283. XThe following script prints \*(L"true\*(R" if and only if the script is
  284. Xinvoked with a -xyz switch.
  285. X.nf
  286. X
  287. X.ne 2
  288. X    #!/usr/bin/perl -s
  289. X    if ($xyz) { print "true\en"; }
  290. X
  291. X.fi
  292. X.TP 5
  293. X.B \-S
  294. Xmakes perl use the PATH environment variable to search for the script
  295. X(unless the name of the script starts with a slash).
  296. XTypically this is used to emulate #! startup on machines that don't
  297. Xsupport #!, in the following manner:
  298. X.nf
  299. X
  300. X    #!/usr/bin/perl
  301. X    eval "exec /usr/bin/perl -S $0 $*"
  302. X        if $running_under_some_shell;
  303. X
  304. X.fi
  305. XThe system ignores the first line and feeds the script to /bin/sh,
  306. Xwhich proceeds to try to execute the perl script as a shell script.
  307. XThe shell executes the second line as a normal shell command, and thus
  308. Xstarts up the perl interpreter.
  309. XOn some systems $0 doesn't always contain the full pathname,
  310. Xso the -S tells perl to search for the script if necessary.
  311. XAfter perl locates the script, it parses the lines and ignores them because
  312. Xthe variable $running_under_some_shell is never true.
  313. X.TP 5
  314. X.B \-U
  315. Xallows perl to do unsafe operations.
  316. XCurrently the only "unsafe" operation is the unlinking of directories while
  317. Xrunning as superuser.
  318. X.TP 5
  319. X.B \-v
  320. Xprints the version and patchlevel of your perl executable.
  321. X.TP 5
  322. X.B \-w
  323. Xprints warnings about identifiers that are mentioned only once, and scalar
  324. Xvariables that are used before being set.
  325. XAlso warns about redefined subroutines, and references to undefined
  326. Xsubroutines and filehandles.
  327. X.Sh "Data Types and Objects"
  328. X.PP
  329. XPerl has about two and a half data types: scalars, arrays of scalars, and
  330. Xassociative arrays.
  331. XScalars and arrays of scalars are first class objects, for the most part,
  332. Xin the sense that they can be used as a whole as values in an expression.
  333. XAssociative arrays can only be accessed on an association by association basis;
  334. Xthey don't have a value as a whole (at least not yet).
  335. X.PP
  336. XScalars are interpreted as strings or numbers as appropriate.
  337. XA scalar is interpreted as TRUE in the boolean sense if it is not the null
  338. Xstring or 0.
  339. XBooleans returned by operators are 1 for true and '0' or '' (the null
  340. Xstring) for false.
  341. X.PP
  342. XReferences to scalar variables always begin with \*(L'$\*(R', even when referring
  343. Xto a scalar that is part of an array.
  344. XThus:
  345. X.nf
  346. X
  347. X.ne 3
  348. X    $days    \h'|2i'# a simple scalar variable
  349. X    $days[28]    \h'|2i'# 29th element of array @days
  350. X    $days{'Feb'}\h'|2i'# one value from an associative array
  351. X    $#days    \h'|2i'# last index of array @days
  352. X
  353. Xbut entire arrays are denoted by \*(L'@\*(R':
  354. X
  355. X    @days    \h'|2i'# ($days[0], $days[1],\|.\|.\|. $days[n])
  356. X
  357. X.fi
  358. X.PP
  359. XAny of these five constructs may server as an lvalue,
  360. Xthat is, may be assigned to.
  361. X(You may also use an assignment to one of these lvalues as an lvalue in
  362. Xcertain contexts\*(--see s, tr and chop.)
  363. XYou may find the length of array @days by evaluating
  364. X\*(L"$#days\*(R", as in
  365. X.IR csh .
  366. X(Actually, it's not the length of the array, it's the subscript of the last element, since there is (ordinarily) a 0th element.)
  367. XAssigning to $#days changes the length of the array.
  368. XShortening an array by this method does not actually destroy any values.
  369. XLengthening an array that was previously shortened recovers the values that
  370. Xwere in those elements.
  371. XYou can also gain some measure of efficiency by preextending an array that
  372. Xis going to get big.
  373. X(You can also extend an array by assigning to an element that is off the
  374. Xend of the array.
  375. XThis differs from assigning to $#whatever in that intervening values
  376. Xare set to null rather than recovered.)
  377. XYou can truncate an array down to nothing by assigning the null list () to
  378. Xit.
  379. XThe following are exactly equivalent
  380. X.nf
  381. X
  382. X    @whatever = ();
  383. X    $#whatever = $[ \- 1;
  384. X
  385. X.fi
  386. X.PP
  387. XEvery data type has its own namespace.
  388. XYou can, without fear of conflict, use the same name for a scalar variable,
  389. Xan array, an associative array, a filehandle, a subroutine name, and/or
  390. Xa label.
  391. XSince variable and array references always start with \*(L'$\*(R'
  392. Xor \*(L'@\*(R', the \*(L"reserved\*(R" words aren't in fact reserved
  393. Xwith respect to variable names.
  394. X(They ARE reserved with respect to labels and filehandles, however, which
  395. Xdon't have an initial special character.
  396. XHint: you could say open(LOG,'logfile') rather than open(log,'logfile').)
  397. XCase IS significant\*(--\*(L"FOO\*(R", \*(L"Foo\*(R" and \*(L"foo\*(R" are all
  398. Xdifferent names.
  399. XNames which start with a letter may also contain digits and underscores.
  400. XNames which do not start with a letter are limited to one character,
  401. Xe.g. \*(L"$%\*(R" or \*(L"$$\*(R".
  402. X(Many one character names have a predefined significance to
  403. X.I perl.
  404. XMore later.)
  405. X.PP
  406. XString literals are delimited by either single or double quotes.
  407. XThey work much like shell quotes:
  408. Xdouble-quoted string literals are subject to backslash and variable
  409. Xsubstitution; single-quoted strings are not.
  410. XThe usual backslash rules apply for making characters such as newline, tab, etc.
  411. XYou can also embed newlines directly in your strings, i.e. they can end on
  412. Xa different line than they begin.
  413. XThis is nice, but if you forget your trailing quote, the error will not be
  414. Xreported until perl finds another line containing the quote character, which
  415. Xmay be much further on in the script.
  416. XVariable substitution inside strings is limited (currently) to simple scalar variables.
  417. XThe following code segment prints out \*(L"The price is $100.\*(R"
  418. X.nf
  419. X
  420. X.ne 2
  421. X    $Price = '$100';\h'|3.5i'# not interpreted
  422. X    print "The price is $Price.\e\|n";\h'|3.5i'# interpreted
  423. X
  424. X.fi
  425. XNote that you can put curly brackets around the identifier to delimit it
  426. Xfrom following alphanumerics.
  427. X.PP
  428. XArray literals are denoted by separating individual values by commas, and
  429. Xenclosing the list in parentheses.
  430. XIn a context not requiring an array value, the value of the array literal
  431. Xis the value of the final element, as in the C comma operator.
  432. XFor example,
  433. X.nf
  434. X
  435. X.ne 4
  436. X    @foo = ('cc', '\-E', $bar);
  437. X
  438. Xassigns the entire array value to array foo, but
  439. X
  440. X    $foo = ('cc', '\-E', $bar);
  441. X
  442. X.fi
  443. Xassigns the value of variable bar to variable foo.
  444. XArray lists may be assigned to if and only if each element of the list
  445. Xis an lvalue:
  446. X.nf
  447. X
  448. X    ($a, $b, $c) = (1, 2, 3);
  449. X
  450. X    ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  451. X
  452. X.fi
  453. XArray assignment returns the number of elements assigned.
  454. X.PP
  455. XNumeric literals are specified in any of the usual floating point or
  456. Xinteger formats.
  457. X.PP
  458. XThere are several other pseudo-literals that you should know about.
  459. XIf a string is enclosed by backticks (grave accents), it first undergoes
  460. Xvariable substitution just like a double quoted string.
  461. XIt is then interpreted as a command, and the output of that command
  462. Xis the value of the pseudo-literal, like in a shell.
  463. XThe command is executed each time the pseudo-literal is evaluated.
  464. XThe status value of the command is returned in $? (see Predefined Names
  465. Xfor the interpretation of $?).
  466. XUnlike in \f2csh\f1, no translation is done on the return
  467. Xdata\*(--newlines remain newlines.
  468. XUnlike in any of the shells, single quotes do not hide variable names
  469. Xin the command from interpretation.
  470. XTo pass a $ through to the shell you need to hide it with a backslash.
  471. X.PP
  472. XEvaluating a filehandle in angle brackets yields the next line
  473. Xfrom that file (newline included, so it's never false until EOF).
  474. XOrdinarily you must assign that value to a variable,
  475. Xbut there is one situation where in which an automatic assignment happens.
  476. XIf (and only if) the input symbol is the only thing inside the conditional of a
  477. X.I while
  478. Xloop, the value is
  479. Xautomatically assigned to the variable \*(L"$_\*(R".
  480. X(This may seem like an odd thing to you, but you'll use the construct
  481. Xin almost every
  482. X.I perl
  483. Xscript you write.)
  484. XAnyway, the following lines are equivalent to each other:
  485. X.nf
  486. X
  487. X.ne 3
  488. X    while ($_ = <stdin>) {
  489. X    while (<stdin>) {
  490. X    for (\|;\|<stdin>;\|) {
  491. X
  492. X.fi
  493. XThe filehandles
  494. X.IR stdin ,
  495. X.I stdout
  496. Xand
  497. X.I stderr
  498. Xare predefined.
  499. XAdditional filehandles may be created with the
  500. X.I open
  501. Xfunction.
  502. X.PP
  503. XIf a <FILEHANDLE> is used in a context that is looking for an array, an array
  504. Xconsisting of all the input lines is returned, one line per array element.
  505. XIt's easy to make a LARGE data space this way, so use with care.
  506. X.PP
  507. XThe null filehandle <> is special and can be used to emulate the behavior of
  508. X\fIsed\fR and \fIawk\fR.
  509. XInput from <> comes either from standard input, or from each file listed on
  510. Xthe command line.
  511. XHere's how it works: the first time <> is evaluated, the ARGV array is checked,
  512. Xand if it is null, $ARGV[0] is set to '-', which when opened gives you standard
  513. Xinput.
  514. XThe ARGV array is then processed as a list of filenames.
  515. XThe loop
  516. X.nf
  517. X
  518. X.ne 3
  519. X    while (<>) {
  520. X        .\|.\|.            # code for each line
  521. X    }
  522. X
  523. X.ne 10
  524. Xis equivalent to
  525. X
  526. X    unshift(@ARGV, '\-') \|if \|$#ARGV < $[;
  527. X    while ($ARGV = shift) {
  528. X        open(ARGV, $ARGV);
  529. X        while (<ARGV>) {
  530. X            .\|.\|.        # code for each line
  531. X        }
  532. X    }
  533. X
  534. X.fi
  535. Xexcept that it isn't as cumbersome to say.
  536. XIt really does shift array ARGV and put the current filename into
  537. Xvariable ARGV.
  538. XIt also uses filehandle ARGV internally.
  539. XYou can modify @ARGV before the first <> as long as you leave the first
  540. Xfilename at the beginning of the array.
  541. XLine numbers ($.) continue as if the input was one big happy file.
  542. X(But see example under eof for how to reset line numbers on each file.)
  543. X.PP
  544. X.ne 5
  545. XIf you want to set @ARGV to your own list of files, go right ahead.
  546. XIf you want to pass switches into your script, you can
  547. Xput a loop on the front like this:
  548. X.nf
  549. X
  550. X.ne 10
  551. X    while ($_ = $ARGV[0], /\|^\-/\|) {
  552. X        shift;
  553. X        last if /\|^\-\|\-$\|/\|;
  554. X        /\|^\-D\|(.*\|)/ \|&& \|($debug = $1);
  555. X        /\|^\-v\|/ \|&& \|$verbose++;
  556. X        .\|.\|.        # other switches
  557. X    }
  558. X    while (<>) {
  559. X        .\|.\|.        # code for each line
  560. X    }
  561. X
  562. X.fi
  563. XThe <> symbol will return FALSE only once.
  564. XIf you call it again after this it will assume you are processing another
  565. X@ARGV list, and if you haven't set @ARGV, will input from stdin.
  566. X.PP
  567. XIf the string inside the angle brackets is a reference to a scalar variable
  568. X(e.g. <$foo>),
  569. Xthen that variable contains the name of the filehandle to input from.
  570. X.PP
  571. XIf the string inside angle brackets is not a filehandle, it is interpreted
  572. Xas a filename pattern to be globbed, and either an array of filenames or the
  573. Xnext filename in the list is returned, depending on context.
  574. XOne level of $ interpretation is done first, but you can't say <$foo>
  575. Xbecause that's an indirect filehandle as explained in the previous
  576. Xparagraph.
  577. XYou could insert curly brackets to force interpretation as a
  578. Xfilename glob: <${foo}>.
  579. XExample:
  580. X.nf
  581. X
  582. X.ne 3
  583. X    while (<*.c>) {
  584. X        chmod 0644,$_;
  585. X    }
  586. X
  587. Xis equivalent to
  588. X
  589. X.ne 5
  590. X    open(foo,"echo *.c | tr -s ' \et\er\ef' '\e\e012\e\e012\e\e012\e\e012'|");
  591. X    while (<foo>) {
  592. X        chop;
  593. X        chmod 0644,$_;
  594. X    }
  595. X
  596. X.fi
  597. XIn fact, it's currently implemented that way.
  598. X(Which means it will not work on filenames with spaces in them.)
  599. XOf course, the shortest way to do the above is:
  600. X.nf
  601. X
  602. X    chmod 0644,<*.c>;
  603. X
  604. X.fi
  605. X.Sh "Syntax"
  606. X.PP
  607. XA
  608. X.I perl
  609. Xscript consists of a sequence of declarations and commands.
  610. XThe only things that need to be declared in
  611. X.I perl
  612. Xare report formats and subroutines.
  613. XSee the sections below for more information on those declarations.
  614. XAll objects are assumed to start with a null or 0 value.
  615. XThe sequence of commands is executed just once, unlike in
  616. X.I sed
  617. Xand
  618. X.I awk
  619. Xscripts, where the sequence of commands is executed for each input line.
  620. XWhile this means that you must explicitly loop over the lines of your input file
  621. X(or files), it also means you have much more control over which files and which
  622. Xlines you look at.
  623. X(Actually, I'm lying\*(--it is possible to do an implicit loop with either the
  624. X.B \-n
  625. Xor
  626. X.B \-p
  627. Xswitch.)
  628. X.PP
  629. XA declaration can be put anywhere a command can, but has no effect on the
  630. Xexecution of the primary sequence of commands.
  631. XTypically all the declarations are put at the beginning or the end of the script.
  632. X.PP
  633. X.I Perl
  634. Xis, for the most part, a free-form language.
  635. X(The only exception to this is format declarations, for fairly obvious reasons.)
  636. XComments are indicated by the # character, and extend to the end of the line.
  637. XIf you attempt to use /* */ C comments, it will be interpreted either as
  638. Xdivision or pattern matching, depending on the context.
  639. XSo don't do that.
  640. X.Sh "Compound statements"
  641. XIn
  642. X.IR perl ,
  643. Xa sequence of commands may be treated as one command by enclosing it
  644. Xin curly brackets.
  645. XWe will call this a BLOCK.
  646. X.PP
  647. XThe following compound commands may be used to control flow:
  648. X.nf
  649. X
  650. X.ne 4
  651. X    if (EXPR) BLOCK
  652. X    if (EXPR) BLOCK else BLOCK
  653. X    if (EXPR) BLOCK elsif (EXPR) BLOCK .\|.\|. else BLOCK
  654. X    LABEL while (EXPR) BLOCK
  655. X    LABEL while (EXPR) BLOCK continue BLOCK
  656. X    LABEL for (EXPR; EXPR; EXPR) BLOCK
  657. X    LABEL foreach VAR (ARRAY) BLOCK
  658. X    LABEL BLOCK continue BLOCK
  659. X
  660. X.fi
  661. XNote that, unlike C and Pascal, these are defined in terms of BLOCKs, not
  662. Xstatements.
  663. XThis means that the curly brackets are \fIrequired\fR\*(--no dangling statements allowed.
  664. XIf you want to write conditionals without curly brackets there are several
  665. Xother ways to do it.
  666. XThe following all do the same thing:
  667. X.nf
  668. X
  669. X.ne 5
  670. X    if (!open(foo)) { die "Can't open $foo"; }
  671. X    die "Can't open $foo" unless open(foo);
  672. X    open(foo) || die "Can't open $foo";    # foo or bust!
  673. X    open(foo) ? die "Can't open $foo" : 'hi mom';
  674. X                # a bit exotic, that last one
  675. X
  676. X.fi
  677. X.PP
  678. XThe
  679. X.I if
  680. Xstatement is straightforward.
  681. XSince BLOCKs are always bounded by curly brackets, there is never any
  682. Xambiguity about which
  683. X.I if
  684. Xan
  685. X.I else
  686. Xgoes with.
  687. XIf you use
  688. X.I unless
  689. Xin place of
  690. X.IR if ,
  691. Xthe sense of the test is reversed.
  692. X.PP
  693. XThe
  694. X.I while
  695. Xstatement executes the block as long as the expression is true
  696. X(does not evaluate to the null string or 0).
  697. XThe LABEL is optional, and if present, consists of an identifier followed by
  698. Xa colon.
  699. XThe LABEL identifies the loop for the loop control statements
  700. X.IR next ,
  701. X.I last
  702. Xand
  703. X.I redo
  704. X(see below).
  705. XIf there is a
  706. X.I continue
  707. XBLOCK, it is always executed just before
  708. Xthe conditional is about to be evaluated again, similarly to the third part
  709. Xof a
  710. X.I for
  711. Xloop in C.
  712. XThus it can be used to increment a loop variable, even when the loop has
  713. Xbeen continued via the
  714. X.I next
  715. Xstatement (similar to the C \*(L"continue\*(R" statement).
  716. X.PP
  717. XIf the word
  718. X.I while
  719. Xis replaced by the word
  720. X.IR until ,
  721. Xthe sense of the test is reversed, but the conditional is still tested before
  722. Xthe first iteration.
  723. X.PP
  724. XIn either the
  725. X.I if
  726. Xor the
  727. X.I while
  728. Xstatement, you may replace \*(L"(EXPR)\*(R" with a BLOCK, and the conditional
  729. Xis true if the value of the last command in that block is true.
  730. X.PP
  731. XThe
  732. X.I for
  733. Xloop works exactly like the corresponding
  734. X.I while
  735. Xloop:
  736. X.nf
  737. X
  738. X.ne 12
  739. X    for ($i = 1; $i < 10; $i++) {
  740. X        .\|.\|.
  741. X    }
  742. X
  743. Xis the same as
  744. X
  745. X    $i = 1;
  746. X    while ($i < 10) {
  747. X        .\|.\|.
  748. X    } continue {
  749. X        $i++;
  750. X    }
  751. X.fi
  752. X.PP
  753. XThe foreach loop iterates over a normal array value and sets the variable
  754. XVAR to be each element of the array in turn.
  755. XThe "foreach" keyword is actually identical to the "for" keyword,
  756. Xso you can use "foreach" for readability or "for" for brevity.
  757. XIf VAR is omitted, $_ is set to each value.
  758. XIf ARRAY is an actual array (as opposed to an expression returning an array
  759. Xvalue), you can modify each element of the array
  760. Xby modifying VAR inside the loop.
  761. XExamples:
  762. X.nf
  763. X
  764. X.ne 5
  765. X    for (@ary) { s/foo/bar/; }
  766. X
  767. X    foreach $elem (@elements) {
  768. X        $elem *= 2;
  769. X    }
  770. X
  771. X    for ((10,9,8,7,6,5,4,3,2,1,'BOOM')) {
  772. X        print $_,"\en"; sleep(1);
  773. X    }
  774. X
  775. X.ne 3
  776. X    foreach $item (split(/:[\e\e\en:]*/,$ENV{'TERMCAP'}) {
  777. X        print "Item: $item\en";
  778. X    }
  779. X.fi
  780. X.PP
  781. XThe BLOCK by itself (labeled or not) is equivalent to a loop that executes
  782. Xonce.
  783. XThus you can use any of the loop control statements in it to leave or
  784. Xrestart the block.
  785. XThe
  786. X.I continue
  787. Xblock is optional.
  788. XThis construct is particularly nice for doing case structures.
  789. X.nf
  790. X
  791. X.ne 6
  792. X    foo: {
  793. X        if (/abc/) { $abc = 1; last foo; }
  794. X        if (/def/) { $def = 1; last foo; }
  795. X        if (/xyz/) { $xyz = 1; last foo; }
  796. X        $nothing = 1;
  797. X    }
  798. X
  799. X.fi
  800. XIt's also nice for exiting subroutines early.
  801. XNote the double curly brackets:
  802. X.nf
  803. X
  804. X.ne 8
  805. X    sub tokenize {{
  806. X        .\|.\|.
  807. X        if (/foo/) {
  808. X            23;        # return value
  809. X            last;
  810. X        }
  811. X        .\|.\|.
  812. X    }}
  813. X
  814. X.fi
  815. X.Sh "Simple statements"
  816. XThe only kind of simple statement is an expression evaluated for its side
  817. Xeffects.
  818. XEvery expression (simple statement) must be terminated with a semicolon.
  819. XNote that this is like C, but unlike Pascal (and
  820. X.IR awk ).
  821. X.PP
  822. XAny simple statement may optionally be followed by a
  823. Xsingle modifier, just before the terminating semicolon.
  824. XThe possible modifiers are:
  825. X.nf
  826. X
  827. X.ne 4
  828. X    if EXPR
  829. X    unless EXPR
  830. X    while EXPR
  831. X    until EXPR
  832. X
  833. X.fi
  834. XThe
  835. X.I if
  836. Xand
  837. X.I unless
  838. Xmodifiers have the expected semantics.
  839. XThe
  840. X.I while
  841. Xand
  842. X.I until
  843. Xmodifiers also have the expected semantics (conditional evaluated first),
  844. Xexcept when applied to a do-BLOCK command,
  845. Xin which case the block executes once before the conditional is evaluated.
  846. XThis is so that you can write loops like:
  847. X.nf
  848. X
  849. X.ne 4
  850. X    do {
  851. X        $_ = <stdin>;
  852. X        .\|.\|.
  853. X    } until $_ \|eq \|".\|\e\|n";
  854. X
  855. X.fi
  856. X(See the
  857. X.I do
  858. Xoperator below.  Note also that the loop control commands described later will
  859. XNOT work in this construct, since modifiers don't take loop labels.
  860. XSorry.)
  861. X.Sh "Expressions"
  862. XSince
  863. X.I perl
  864. Xexpressions work almost exactly like C expressions, only the differences
  865. Xwill be mentioned here.
  866. X.PP
  867. XHere's what
  868. X.I perl
  869. Xhas that C doesn't:
  870. X.Ip (\|) 8 3
  871. XThe null list, used to initialize an array to null.
  872. X.Ip . 8
  873. XConcatenation of two strings.
  874. X.Ip .= 8
  875. XThe corresponding assignment operator.
  876. X.Ip eq 8
  877. XString equality (== is numeric equality).
  878. XFor a mnemonic just think of \*(L"eq\*(R" as a string.
  879. X(If you are used to the
  880. X.I awk
  881. Xbehavior of using == for either string or numeric equality
  882. Xbased on the current form of the comparands, beware!
  883. XYou must be explicit here.)
  884. X.Ip ne 8
  885. XString inequality (!= is numeric inequality).
  886. X.Ip lt 8
  887. XString less than.
  888. X.Ip gt 8
  889. XString greater than.
  890. X.Ip le 8
  891. XString less than or equal.
  892. X.Ip ge 8
  893. XString greater than or equal.
  894. X.Ip =~ 8 2
  895. XCertain operations search or modify the string \*(L"$_\*(R" by default.
  896. XThis operator makes that kind of operation work on some other string.
  897. XThe right argument is a search pattern, substitution, or translation.
  898. XThe left argument is what is supposed to be searched, substituted, or
  899. Xtranslated instead of the default \*(L"$_\*(R".
  900. XThe return value indicates the success of the operation.
  901. X(If the right argument is an expression other than a search pattern,
  902. Xsubstitution, or translation, it is interpreted as a search pattern
  903. Xat run time.
  904. XThis is less efficient than an explicit search, since the pattern must
  905. Xbe compiled every time the expression is evaluated.)
  906. XThe precedence of this operator is lower than unary minus and autoincrement/decrement, but higher than everything else.
  907. X.Ip !~ 8
  908. XJust like =~ except the return value is negated.
  909. X.Ip x 8
  910. XThe repetition operator.
  911. XReturns a string consisting of the left operand repeated the
  912. Xnumber of times specified by the right operand.
  913. X.nf
  914. X
  915. X    print '-' x 80;        # print row of dashes
  916. X    print '-' x80;        # illegal, x80 is identifier
  917. X
  918. X    print "\et" x ($tab/8), ' ' x ($tab%8);    # tab over
  919. X
  920. X.fi
  921. X.Ip x= 8
  922. XThe corresponding assignment operator.
  923. X.Ip .. 8
  924. XThe range operator, which is bistable.
  925. XEach .. operator maintains its own boolean state.
  926. XIt is false as long as its left operand is false.
  927. XOnce the left operand is true, the range operator stays true
  928. Xuntil the right operand is true,
  929. XAFTER which the range operator becomes false again.
  930. X(It doesn't become false till the next time the range operator evaluated.
  931. XIt can become false on the same evaluation it became true, but it still returns
  932. Xtrue once.)
  933. XThe right operand is not evaluated while the operator is in the "false" state,
  934. Xand the left operand is not evaluated while the operator is in the "true" state.
  935. XThe .. operator is primarily intended for doing line number ranges after
  936. Xthe fashion of \fIsed\fR or \fIawk\fR.
  937. XThe precedence is a little lower than || and &&.
  938. XThe value returned is either the null string for false, or a sequence number
  939. X(beginning with 1) for true.
  940. XThe sequence number is reset for each range encountered.
  941. XThe final sequence number in a range has the string 'E0' appended to it, which
  942. Xdoesn't affect its numeric value, but gives you something to search for if you
  943. Xwant to exclude the endpoint.
  944. XYou can exclude the beginning point by waiting for the sequence number to be
  945. Xgreater than 1.
  946. XIf either operand of .. is static, that operand is implicitly compared to
  947. Xthe $. variable, the current line number.
  948. XExamples:
  949. X.nf
  950. X
  951. X.ne 5
  952. X    if (101 .. 200) { print; }    # print 2nd hundred lines
  953. X
  954. X    next line if (1 .. /^$/);    # skip header lines
  955. X
  956. X    s/^/> / if (/^$/ .. eof());    # quote body
  957. X
  958. X.fi
  959. X.Ip \-x 8
  960. XA file test.
  961. XThis unary operator takes one argument, either a filename or a filehandle,
  962. Xand tests the associated file to see if something is true about it.
  963. XIf the argument is omitted, tests $_, except for \-t, which tests stdin.
  964. XIt returns 1 for true and '' for false.
  965. XPrecedence is higher than logical and relational operators, but lower than
  966. Xarithmetic operators.
  967. XThe operator may be any of:
  968. X.nf
  969. X    \-r    File is readable by effective uid.
  970. X    \-w    File is writeable by effective uid.
  971. X    \-x    File is executable by effective uid.
  972. X    \-o    File is owned by effective uid.
  973. X    \-R    File is readable by real uid.
  974. X    \-W    File is writeable by real uid.
  975. X    \-X    File is executable by real uid.
  976. X    \-O    File is owned by real uid.
  977. X    \-e    File exists.
  978. X    \-z    File has zero size.
  979. X    \-s    File has non-zero size.
  980. X    \-f    File is a plain file.
  981. X    \-d    File is a directory.
  982. X    \-l    File is a symbolic link.
  983. X    \-p    File is a named pipe (FIFO).
  984. X    \-S    File is a socket.
  985. X    \-b    File is a block special file.
  986. X    \-c    File is a character special file.
  987. X    \-u    File has setuid bit set.
  988. X    \-g    File has setgid bit set.
  989. X    \-k    File has sticky bit set.
  990. X    \-t    Filehandle is opened to a tty.
  991. X    \-T    File is a text file.
  992. X    \-B    File is a binary file (opposite of \-T).
  993. X
  994. X.fi
  995. XThe interpretation of the file permission operators \-r, \-R, \-w, \-W, \-x and \-X
  996. Xis based solely on the mode of the file and the uids and gids of the user.
  997. XThere may be other reasons you can't actually read, write or execute the file.
  998. XAlso note that, for the superuser, \-r, \-R, \-w and \-W always return 1, and 
  999. X\-x and \-X return 1 if any execute bit is set in the mode.
  1000. XScripts run by the superuser may thus need to do a stat() in order to determine
  1001. Xthe actual mode of the file, or temporarily set the uid to something else.
  1002. X.Sp
  1003. XExample:
  1004. X.nf
  1005. X.ne 7
  1006. X    
  1007. X    while (<>) {
  1008. X        chop;
  1009. X        next unless \-f $_;    # ignore specials
  1010. X        .\|.\|.
  1011. X    }
  1012. X
  1013. X.fi
  1014. XNote that -s/a/b/ does not do a negated substitution.
  1015. XSaying -exp($foo) still works as expected, however\*(--only single letters
  1016. Xfollowing a minus are interpreted as file tests.
  1017. X.Sp
  1018. XThe \-T and \-B switches work as follows.
  1019. XThe first block or so of the file is examined for odd characters such as
  1020. Xstrange control codes or metacharacters.
  1021. XIf too many odd characters (>10%) are found, it's a \-B file, otherwise it's a \-T file.
  1022. XAlso, any file containing null in the first block is considered a binary file.
  1023. XIf \-T or \-B is used on a filehandle, the current stdio buffer is examined
  1024. Xrather than the first block.
  1025. XSince input doesn't work well on binary files you should probably test a
  1026. Xfilehandle before doing any input if you're unsure of the nature of the
  1027. Xfilehandle you've been handed (usually via stdin).
  1028. XBoth \-T and \-B return TRUE on a null file, or a file at EOF when testing
  1029. Xa filehandle.
  1030. X.PP
  1031. XHere is what C has that
  1032. X.I perl
  1033. Xdoesn't:
  1034. X.Ip "unary &" 12
  1035. XAddress-of operator.
  1036. X.Ip "unary *" 12
  1037. XDereference-address operator.
  1038. X.Ip "(TYPE)" 12
  1039. XType casting operator.
  1040. X.PP
  1041. XLike C,
  1042. X.I perl
  1043. Xdoes a certain amount of expression evaluation at compile time, whenever
  1044. Xit determines that all of the arguments to an operator are static and have
  1045. Xno side effects.
  1046. XIn particular, string concatenation happens at compile time between literals that don't do variable substitution.
  1047. XBackslash interpretation also happens at compile time.
  1048. XYou can say
  1049. X.nf
  1050. X
  1051. X.ne 2
  1052. X    'Now is the time for all' . "\|\e\|n" .
  1053. X    'good men to come to.'
  1054. X
  1055. X.fi
  1056. Xand this all reduces to one string internally.
  1057. X.PP
  1058. XThe autoincrement operator has a little extra built-in magic to it.
  1059. XIf you increment a variable that is numeric, or that has ever been used in
  1060. Xa numeric context, you get a normal increment.
  1061. XIf, however, the variable has only been used in string contexts since it
  1062. Xwas set, and has a value that is not null and matches the
  1063. Xpattern /^[a-zA-Z]*[0-9]*$/, the increment is done
  1064. Xas a string, preserving each character within its range, with carry:
  1065. X.nf
  1066. X
  1067. X    print ++($foo = '99');    # prints '100'
  1068. X    print ++($foo = 'a0');    # prints 'a1'
  1069. X    print ++($foo = 'Az');    # prints 'Ba'
  1070. X    print ++($foo = 'zz');    # prints 'aaa'
  1071. X
  1072. X.fi
  1073. XThe autodecrement is not magical.
  1074. X.PP
  1075. XAlong with the literals and variables mentioned earlier,
  1076. Xthe following operations can serve as terms in an expression.
  1077. XSome of these operations take a LIST as an argument.
  1078. XSuch a list can consist of any combination of scalar arguments or arrays;
  1079. Xthe arrays will be included in the list as if each individual element were
  1080. Xinterpolated at that point in the list.
  1081. X.Ip "/PATTERN/i" 8 4
  1082. XSearches a string for a pattern, and returns true (1) or false ('').
  1083. XIf no string is specified via the =~ or !~ operator,
  1084. Xthe $_ string is searched.
  1085. X(The string specified with =~ need not be an lvalue\*(--it may be the result of an expression evaluation, but remember the =~ binds rather tightly.)
  1086. XSee also the section on regular expressions.
  1087. X.Sp
  1088. XIf you prepend an `m' you can use any pair of characters as delimiters.
  1089. XThis is particularly useful for matching Unix path names that contain `/'.
  1090. XIf the final delimiter is followed by the optional letter `i', the matching is
  1091. Xdone in a case-insensitive manner.
  1092. X.Sp
  1093. XIf used in a context that requires an array value, a pattern match returns an
  1094. Xarray consisting of the subexpressions matched by the parens in pattern,
  1095. Xi.e. ($1, $2, $3.\|.\|.).
  1096. X.Sp
  1097. XExamples:
  1098. X.nf
  1099. X
  1100. X.ne 4
  1101. X    open(tty, '/dev/tty');
  1102. X    <tty> \|=~ \|/\|^y\|/i \|&& \|do foo(\|);    # do foo if desired
  1103. X
  1104. X    if (/Version: \|*\|([0-9.]*\|)\|/\|) { $version = $1; }
  1105. X
  1106. X    next if m#^/usr/spool/uucp#;
  1107. X
  1108. X    if (($F1,$F2,$Etc) = ($foo =~ /^(\eS+)\es+(\eS+)\es*(.*)/))
  1109. X
  1110. X.fi
  1111. XThis last example splits $foo into the first two words and the remainder
  1112. Xof the line, and assigns those three fields to $F1, $F2 and $Etc.
  1113. XThe conditional is true if any variables were assigned, i.e. if the pattern
  1114. Xmatched.
  1115. X.Ip "?PATTERN?" 8 4
  1116. XThis is just like the /pattern/ search, except that it matches only once between
  1117. Xcalls to the
  1118. X.I reset
  1119. Xoperator.
  1120. XThis is a useful optimization when you only want to see the first occurence of
  1121. Xsomething in each file of a set of files, for instance.
  1122. X.Ip "chdir EXPR" 8 2
  1123. XChanges the working directory to EXPR, if possible.
  1124. XReturns 1 upon success, 0 otherwise.
  1125. XSee example under die().
  1126. X.Ip "chmod LIST" 8 2
  1127. XChanges the permissions of a list of files.
  1128. XThe first element of the list must be the numerical mode.
  1129. XReturns the number of files successfully changed.
  1130. X.nf
  1131. X
  1132. X.ne 2
  1133. X    $cnt = chmod 0755,'foo','bar';
  1134. X    chmod 0755,@executables;
  1135. X
  1136. X.fi
  1137. X.Ip "chop(VARIABLE)" 8 5
  1138. X.Ip "chop" 8
  1139. XChops off the last character of a string and returns it.
  1140. XIt's used primarily to remove the newline from the end of an input record,
  1141. Xbut is much more efficient than s/\en// because it neither scans nor copies
  1142. Xthe string.
  1143. XIf VARIABLE is omitted, chops $_.
  1144. XExample:
  1145. X.nf
  1146. X
  1147. X.ne 5
  1148. X    while (<>) {
  1149. X        chop;    # avoid \en on last field
  1150. X        @array = split(/:/);
  1151. X        .\|.\|.
  1152. X    }
  1153. X
  1154. X.fi
  1155. XYou can actually chop anything that's an lvalue, including an assignment:
  1156. X.nf
  1157. X
  1158. X    chop($cwd = `pwd`);
  1159. X
  1160. X.fi
  1161. X.Ip "chown LIST" 8 2
  1162. XChanges the owner (and group) of a list of files.
  1163. XThe first two elements of the list must be the NUMERICAL uid and gid,
  1164. Xin that order.
  1165. XReturns the number of files successfully changed.
  1166. X.nf
  1167. X
  1168. X.ne 2
  1169. X    $cnt = chown $uid,$gid,'foo','bar';
  1170. X    chown $uid,$gid,@filenames;
  1171. X
  1172. X.fi
  1173. X.ne 23
  1174. XHere's an example of looking up non-numeric uids:
  1175. X.nf
  1176. X
  1177. X    print "User: ";
  1178. X    $user = <stdin>;
  1179. X    chop($user);
  1180. X    print "Files: "
  1181. X    $pattern = <stdin>;
  1182. X    chop($pattern);
  1183. X    open(pass,'/etc/passwd') || die "Can't open passwd";
  1184. X    while (<pass>) {
  1185. X        ($login,$pass,$uid,$gid) = split(/:/);
  1186. X        $uid{$login} = $uid;
  1187. X        $gid{$login} = $gid;
  1188. X    }
  1189. X    @ary = <$pattern>;    # get filenames
  1190. X    if ($uid{$user} eq '') {
  1191. X        die "$user not in passwd file";
  1192. X    }
  1193. X    else {
  1194. X        unshift(@ary,$uid{$user},$gid{$user});
  1195. X        chown @ary;
  1196. X    }
  1197. X
  1198. X.fi
  1199. X.Ip "close(FILEHANDLE)" 8 5
  1200. X.Ip "close FILEHANDLE" 8
  1201. XCloses the file or pipe associated with the file handle.
  1202. XYou don't have to close FILEHANDLE if you are immediately going to
  1203. Xdo another open on it, since open will close it for you.
  1204. X(See
  1205. X.IR open .)
  1206. XHowever, an explicit close on an input file resets the line counter ($.), while
  1207. Xthe implicit close done by
  1208. X.I open
  1209. Xdoes not.
  1210. XAlso, closing a pipe will wait for the process executing on the pipe to complete,
  1211. Xin case you want to look at the output of the pipe afterwards.
  1212. XExample:
  1213. X.nf
  1214. X
  1215. X.ne 4
  1216. X    open(output,'|sort >foo');    # pipe to sort
  1217. X    .\|.\|.    # print stuff to output
  1218. X    close(output);        # wait for sort to finish
  1219. X    open(input,'foo');    # get sort's results
  1220. X
  1221. X.fi
  1222. XFILEHANDLE may be an expression whose value gives the real filehandle name.
  1223. X.Ip "crypt(PLAINTEXT,SALT)" 8 6
  1224. XEncrypts a string exactly like the crypt() function in the C library.
  1225. XUseful for checking the password file for lousy passwords.
  1226. XOnly the guys wearing white hats should do this.
  1227. X.Ip "delete $ASSOC{KEY}" 8 6
  1228. XDeletes the specified value from the specified associative array.
  1229. XReturns the deleted value;
  1230. XThe following deletes all the values of an associative array:
  1231. X.nf
  1232. X
  1233. X.ne 3
  1234. X    foreach $key (keys(ARRAY)) {
  1235. X        delete $ARRAY{$key};
  1236. X    }
  1237. X
  1238. X.fi
  1239. X(But it would be faster to use the reset command.)
  1240. X.Ip "die EXPR" 8 6
  1241. XPrints the value of EXPR to stderr and exits with the current value of $!
  1242. X(errno).
  1243. XIf $! is 0, exits with the value of ($? >> 8) (`command` status).
  1244. XIf ($? >> 8) is 0, exits with 255.
  1245. XEquivalent examples:
  1246. X.nf
  1247. X
  1248. X.ne 3
  1249. X    die "Can't cd to spool.\en" unless chdir '/usr/spool/news';
  1250. X
  1251. X    chdir '/usr/spool/news' || die "Can't cd to spool.\en" 
  1252. X
  1253. X.fi
  1254. X.Sp
  1255. XIf the value of EXPR does not end in a newline, the current script line
  1256. Xnumber and input line number (if any) are also printed, and a newline is
  1257. Xsupplied.
  1258. XHint: sometimes appending ", stopped" to your message will cause it to make
  1259. Xbetter sense when the string "at foo line 123" is appended.
  1260. XSuppose you are running script "canasta".
  1261. X.nf
  1262. X
  1263. X.ne 7
  1264. X    die "/etc/games is no good";
  1265. X    die "/etc/games is no good, stopped";
  1266. X
  1267. Xproduce, respectively
  1268. X
  1269. X    /etc/games is no good at canasta line 123.
  1270. X    /etc/games is no good, stopped at canasta line 123.
  1271. X
  1272. X.fi
  1273. XSee also
  1274. X.IR exit .
  1275. X.Ip "do BLOCK" 8 4
  1276. XReturns the value of the last command in the sequence of commands indicated
  1277. Xby BLOCK.
  1278. XWhen modified by a loop modifier, executes the BLOCK once before testing the
  1279. Xloop condition.
  1280. X(On other statements the loop modifiers test the conditional first.)
  1281. X.Ip "do SUBROUTINE (LIST)" 8 3
  1282. XExecutes a SUBROUTINE declared by a
  1283. X.I sub
  1284. Xdeclaration, and returns the value
  1285. Xof the last expression evaluated in SUBROUTINE.
  1286. XIf you pass arrays as part of LIST you may wish to pass the length
  1287. Xof the array in front of each array.
  1288. X(See the section on subroutines later on.)
  1289. XSUBROUTINE may be a scalar variable, in which case the variable contains
  1290. Xthe name of the subroutine to execute.
  1291. XThe parentheses are required to avoid confusion with the next form of "do".
  1292. X.Ip "do EXPR" 8 3
  1293. XUses the value of EXPR as a filename and executes the contents of the file
  1294. Xas a perl script.
  1295. XIt's primary use is to include subroutines from a perl subroutine library.
  1296. X.nf
  1297. X    do 'stat.pl';
  1298. X
  1299. Xis just like
  1300. X
  1301. X    eval `cat stat.pl`;
  1302. X
  1303. X.fi
  1304. Xexcept that it's more efficient, more concise, keeps track of the current
  1305. Xfilename for error messages, and searches all the -I libraries if the file
  1306. Xisn't in the current directory (see also the @INC array in Predefined Names).
  1307. XIt's the same, however, in that it does reparse the file every time you
  1308. Xcall it, so if you are going to use the file inside a loop you might prefer
  1309. Xto use #include, at the expense of a little more startup time.
  1310. X(The main problem with #include is that cpp doesn't grok # comments--a
  1311. Xworkaround is to use ";#" for standalone comments.)
  1312. XNote that the following are NOT equivalent:
  1313. X.nf
  1314. X
  1315. X.ne 2
  1316. X    do $foo;    # eval a file
  1317. X    do $foo();    # call a subroutine
  1318. X
  1319. X.fi
  1320. X.Ip "each(ASSOC_ARRAY)" 8 6
  1321. XReturns a 2 element array consisting of the key and value for the next
  1322. Xvalue of an associative array, so that you can iterate over it.
  1323. XEntries are returned in an apparently random order.
  1324. XWhen the array is entirely read, a null array is returned (which when
  1325. Xassigned produces a FALSE (0) value).
  1326. XThe next call to each() after that will start iterating again.
  1327. XThe iterator can be reset only by reading all the elements from the array.
  1328. XYou must not modify the array while iterating over it.
  1329. XThere is a single iterator for each associative array, shared by all
  1330. Xeach(), keys() and values() function calls in the program.
  1331. XThe following prints out your environment like the printenv program, only
  1332. Xin a different order:
  1333. X.nf
  1334. X
  1335. X.ne 3
  1336. X    while (($key,$value) = each(ENV)) {
  1337. X        print "$key=$value\en";
  1338. X    }
  1339. X
  1340. X.fi
  1341. XSee also keys() and values().
  1342. X.Ip "eof(FILEHANDLE)" 8 8
  1343. X.Ip "eof" 8
  1344. XReturns 1 if the next read on FILEHANDLE will return end of file, or if
  1345. XFILEHANDLE is not open.
  1346. XFILEHANDLE may be an expression whose value gives the real filehandle name.
  1347. XAn eof without an argument returns the eof status for the last file read.
  1348. XEmpty parentheses () may be used to indicate the pseudo file formed of the
  1349. Xfiles listed on the command line, i.e. eof() is reasonable to use inside
  1350. Xa while (<>) loop to detect the end of only the last file.
  1351. XUse eof(ARGV) or eof without the parens to test EACH file in a while (<>) loop.
  1352. XExamples:
  1353. X.nf
  1354. X
  1355. X.ne 7
  1356. X    # insert dashes just before last line of last file
  1357. X    while (<>) {
  1358. X        if (eof()) {
  1359. X            print "--------------\en";
  1360. X        }
  1361. X        print;
  1362. X    }
  1363. X
  1364. X.ne 7
  1365. X    # reset line numbering on each input file
  1366. X    while (<>) {
  1367. X        print "$.\et$_";
  1368. X        if (eof) {    # Not eof().
  1369. X            close(ARGV);
  1370. X        }
  1371. X    }
  1372. X
  1373. X.fi
  1374. X.Ip "eval EXPR" 8 6
  1375. XEXPR is parsed and executed as if it were a little perl program.
  1376. XIt is executed in the context of the current perl program, so that
  1377. Xany variable settings, subroutine or format definitions remain afterwards.
  1378. XThe value returned is the value of the last expression evaluated, just
  1379. Xas with subroutines.
  1380. XIf there is a syntax error or runtime error, a null string is returned by
  1381. Xeval, and $@ is set to the error message.
  1382. XIf there was no error, $@ is null.
  1383. XIf EXPR is omitted, evaluates $_.
  1384. X.Ip "exec LIST" 8 6
  1385. XIf there is more than one argument in LIST,
  1386. Xcalls execvp() with the arguments in LIST.
  1387. XIf there is only one argument, the argument is checked for shell metacharacters.
  1388. XIf there are any, the entire argument is passed to /bin/sh -c for parsing.
  1389. XIf there are none, the argument is split into words and passed directly to
  1390. Xexecvp(), which is more efficient.
  1391. XNote: exec (and system) do not flush your output buffer, so you may need to
  1392. Xset $| to avoid lost output.
  1393. XExamples:
  1394. X.nf
  1395. X
  1396. X    exec '/bin/echo', 'Your arguments are: ', @ARGV;
  1397. X    exec "sort $outfile | uniq";
  1398. X
  1399. X.fi
  1400. X.Ip "exit EXPR" 8 6
  1401. XEvaluates EXPR and exits immediately with that value.
  1402. XExample:
  1403. X.nf
  1404. X
  1405. X.ne 2
  1406. X    $ans = <stdin>;
  1407. X    exit 0 \|if \|$ans \|=~ \|/\|^[Xx]\|/\|;
  1408. X
  1409. X.fi
  1410. XSee also
  1411. X.IR die .
  1412. X.Ip "exp(EXPR)" 8 3
  1413. XReturns e to the power of EXPR.
  1414. X.Ip "fork" 8 4
  1415. XDoes a fork() call.
  1416. XReturns the child pid to the parent process and 0 to the child process.
  1417. XNote: unflushed buffers remain unflushed in both processes, which means
  1418. Xyou may need to set $| to avoid duplicate output.
  1419. X.Ip "gmtime(EXPR)" 8 4
  1420. XConverts a time as returned by the time function to a 9-element array with
  1421. Xthe time analyzed for the Greenwich timezone.
  1422. XTypically used as follows:
  1423. X.nf
  1424. X
  1425. X.ne 3
  1426. X    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
  1427. X       = gmtime(time);
  1428. X
  1429. X.fi
  1430. XAll array elements are numeric, and come straight out of a struct tm.
  1431. XIn particular this means that $mon has the range 0..11 and $wday has the
  1432. Xrange 0..6.
  1433. X''' End of part 1
  1434. !STUFFY!FUNK!
  1435. echo Extracting makedepend.SH
  1436. sed >makedepend.SH <<'!STUFFY!FUNK!' -e 's/X//'
  1437. Xcase $CONFIG in
  1438. X'')
  1439. X    if test ! -f config.sh; then
  1440. X    ln ../config.sh . || \
  1441. X    ln ../../config.sh . || \
  1442. X    ln ../../../config.sh . || \
  1443. X    (echo "Can't find config.sh."; exit 1)
  1444. X    fi
  1445. X    . ./config.sh
  1446. X    ;;
  1447. Xesac
  1448. Xcase "$0" in
  1449. X*/*) cd `expr X$0 : 'X\(.*\)/'` ;;
  1450. Xesac
  1451. Xecho "Extracting makedepend (with variable substitutions)"
  1452. X$spitshell >makedepend <<!GROK!THIS!
  1453. X$startsh
  1454. X# $Header: makedepend.SH,v 2.0 88/06/05 00:09:11 root Exp $
  1455. X#
  1456. X# $Log:    makedepend.SH,v $
  1457. X# Revision 2.0  88/06/05  00:09:11  root
  1458. X# Baseline version 2.0.
  1459. X# 
  1460. X# 
  1461. X
  1462. Xexport PATH || (echo "OOPS, this isn't sh.  Desperation time.  I will feed myself to sh."; sh \$0; kill \$\$)
  1463. X
  1464. Xcat='$cat'
  1465. Xccflags='$ccflags'
  1466. Xcp='$cp'
  1467. Xcpp='$cppstdin'
  1468. Xecho='$echo'
  1469. Xegrep='$egrep'
  1470. Xexpr='$expr'
  1471. Xmv='$mv'
  1472. Xrm='$rm'
  1473. Xsed='$sed'
  1474. Xsort='$sort'
  1475. Xtest='$test'
  1476. Xtr='$tr'
  1477. Xuniq='$uniq'
  1478. X!GROK!THIS!
  1479. X
  1480. X$spitshell >>makedepend <<'!NO!SUBS!'
  1481. X
  1482. X: the following weeds options from ccflags that are of no interest to cpp
  1483. Xcase "$ccflags" in
  1484. X'');;
  1485. X*)  set X $ccflags
  1486. X    ccflags=''
  1487. X    for flag do
  1488. X    case $flag in
  1489. X    -D*|-I*) ccflags="$ccflags $flag";;
  1490. X    esac
  1491. X    done
  1492. X    ;;
  1493. Xesac
  1494. X
  1495. X$cat /dev/null >.deptmp
  1496. X$rm -f *.c.c c/*.c.c
  1497. Xif test -f Makefile; then
  1498. X    mf=Makefile
  1499. Xelse
  1500. X    mf=makefile
  1501. Xfi
  1502. Xif test -f $mf; then
  1503. X    defrule=`<$mf sed -n        \
  1504. X    -e '/^\.c\.o:.*;/{'        \
  1505. X    -e    's/\$\*\.c//'        \
  1506. X    -e    's/^[^;]*;[     ]*//p'    \
  1507. X    -e    q                \
  1508. X    -e '}'                \
  1509. X    -e '/^\.c\.o: *$/{'        \
  1510. X    -e    N                \
  1511. X    -e    's/\$\*\.c//'        \
  1512. X    -e    's/^.*\n[     ]*//p'        \
  1513. X    -e    q                \
  1514. X    -e '}'`
  1515. Xfi
  1516. Xcase "$defrule" in
  1517. X'') defrule='$(CC) -c $(CFLAGS)' ;;
  1518. Xesac
  1519. X
  1520. Xmake clist || ($echo "Searching for .c files..."; \
  1521. X    $echo *.c */*.c | $tr ' ' '\012' | $egrep -v '\*' >.clist)
  1522. Xfor file in `$cat .clist`; do
  1523. X# for file in `cat /dev/null`; do
  1524. X    case "$file" in
  1525. X    *.c) filebase=`basename $file .c` ;;
  1526. X    *.y) filebase=`basename $file .c` ;;
  1527. X    esac
  1528. X    $echo "Finding dependencies for $filebase.o."
  1529. X    $sed -n <$file >$file.c \
  1530. X    -e "/^${filebase}_init(/q" \
  1531. X    -e '/^#/{' \
  1532. X    -e 's|/\*.*$||' \
  1533. X    -e 's|\\$||' \
  1534. X    -e p \
  1535. X    -e '}'
  1536. X    $cpp -I/usr/local/include -I. $ccflags $file.c | \
  1537. X    $sed \
  1538. X    -e '/^# *[0-9]/!d' \
  1539. X    -e 's/^.*"\(.*\)".*$/'$filebase'.o: \1/' \
  1540. X    -e 's|: \./|: |' \
  1541. X    -e 's|\.c\.c|.c|' | \
  1542. X    $uniq | $sort | $uniq >> .deptmp
  1543. Xdone
  1544. X
  1545. X$sed <Makefile >Makefile.new -e '1,/^# AUTOMATICALLY/!d'
  1546. X
  1547. Xmake shlist || ($echo "Searching for .SH files..."; \
  1548. X    $echo *.SH */*.SH | $tr ' ' '\012' | $egrep -v '\*' >.shlist)
  1549. Xif $test -s .deptmp; then
  1550. X    for file in `cat .shlist`; do
  1551. X    $echo `$expr X$file : 'X\(.*\).SH`: $file config.sh \; \
  1552. X        /bin/sh $file >> .deptmp
  1553. X    done
  1554. X    $echo "Updating Makefile..."
  1555. X    $echo "# If this runs make out of memory, delete /usr/include lines." \
  1556. X    >> Makefile.new
  1557. X    $sed 's|^\(.*\.o:\) *\(.*/.*\.c\) *$|\1 \2; '"$defrule \2|" .deptmp \
  1558. X       >>Makefile.new
  1559. Xelse
  1560. X    make hlist || ($echo "Searching for .h files..."; \
  1561. X    $echo *.h */*.h | $tr ' ' '\012' | $egrep -v '\*' >.hlist)
  1562. X    $echo "You don't seem to have a proper C preprocessor.  Using grep instead."
  1563. X    $egrep '^#include ' `cat .clist` `cat .hlist`  >.deptmp
  1564. X    $echo "Updating Makefile..."
  1565. X    <.clist $sed -n                            \
  1566. X    -e '/\//{'                            \
  1567. X    -e   's|^\(.*\)/\(.*\)\.c|\2.o: \1/\2.c; '"$defrule \1/\2.c|p"    \
  1568. X    -e   d                                \
  1569. X    -e '}'                                \
  1570. X    -e 's|^\(.*\)\.c|\1.o: \1.c|p' >> Makefile.new
  1571. X    <.hlist $sed -n 's|\(.*/\)\(.*\)|s= \2= \1\2=|p' >.hsed
  1572. X    <.deptmp $sed -n 's|c:#include "\(.*\)".*$|o: \1|p' | \
  1573. X       $sed 's|^[^;]*/||' | \
  1574. X       $sed -f .hsed >> Makefile.new
  1575. X    <.deptmp $sed -n 's|c:#include <\(.*\)>.*$|o: /usr/include/\1|p' \
  1576. X       >> Makefile.new
  1577. X    <.deptmp $sed -n 's|h:#include "\(.*\)".*$|h: \1|p' | \
  1578. X       $sed -f .hsed >> Makefile.new
  1579. X    <.deptmp $sed -n 's|h:#include <\(.*\)>.*$|h: /usr/include/\1|p' \
  1580. X       >> Makefile.new
  1581. X    for file in `$cat .shlist`; do
  1582. X    $echo `$expr X$file : 'X\(.*\).SH`: $file config.sh \; \
  1583. X        /bin/sh $file >> Makefile.new
  1584. X    done
  1585. Xfi
  1586. X$rm -f Makefile.old
  1587. X$cp Makefile Makefile.old
  1588. X$cp Makefile.new Makefile
  1589. X$rm Makefile.new
  1590. X$echo "# WARNING: Put nothing here or make depend will gobble it up!" >> Makefile
  1591. X$rm -f .deptmp `sed 's/\.c/.c.c/' .clist` .shlist .clist .hlist .hsed
  1592. X
  1593. X!NO!SUBS!
  1594. X$eunicefix makedepend
  1595. Xchmod +x makedepend
  1596. Xcase `pwd` in
  1597. X*SH)
  1598. X    $rm -f ../makedepend
  1599. X    ln makedepend ../makedepend
  1600. X    ;;
  1601. Xesac
  1602. !STUFFY!FUNK!
  1603. echo Extracting t/op.cond
  1604. sed >t/op.cond <<'!STUFFY!FUNK!' -e 's/X//'
  1605. X#!./perl
  1606. X
  1607. X# $Header: op.cond,v 2.0 88/06/05 00:13:26 root Exp $
  1608. X
  1609. Xprint "1..4\n";
  1610. X
  1611. Xprint 1 ? "ok 1\n" : "not ok 1\n";    # compile time
  1612. Xprint 0 ? "not ok 2\n" : "ok 2\n";
  1613. X
  1614. X$x = 1;
  1615. Xprint $x ? "ok 3\n" : "not ok 3\n";    # run time
  1616. Xprint !$x ? "not ok 4\n" : "ok 4\n";
  1617. !STUFFY!FUNK!
  1618. echo ""
  1619. echo "End of kit 5 (of 15)"
  1620. cat /dev/null >kit5isdone
  1621. run=''
  1622. config=''
  1623. for iskit in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
  1624.     if test -f kit${iskit}isdone; then
  1625.     run="$run $iskit"
  1626.     else
  1627.     todo="$todo $iskit"
  1628.     fi
  1629. done
  1630. case $todo in
  1631.     '')
  1632.     echo "You have run all your kits.  Please read README and then type Configure."
  1633.     chmod 755 Configure
  1634.     ;;
  1635.     *)  echo "You have run$run."
  1636.     echo "You still need to run$todo."
  1637.     ;;
  1638. esac
  1639. : Someone might mail this, so...
  1640. exit
  1641.  
  1642.