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

  1. From: lwall@netlabs.com (Larry Wall)
  2. Newsgroups: comp.sources.misc
  3. Subject: v18i020:  perl - The perl programming language, Part02/36
  4. Message-ID: <1991Apr15.015234.6549@sparky.IMD.Sterling.COM>
  5. Date: 15 Apr 91 01:52:34 GMT
  6. Approved: kent@sparky.imd.sterling.com
  7. X-Checksum-Snefru: 3c60c4e2 36f7a6c1 6200cf17 b78f69c1
  8.  
  9. Submitted-by: Larry Wall <lwall@netlabs.com>
  10. Posting-number: Volume 18, Issue 20
  11. Archive-name: perl/part02
  12.  
  13. [There are 36 kits for perl version 4.0.]
  14.  
  15. #! /bin/sh
  16.  
  17. # Make a new directory for the perl sources, cd to it, and run kits 1
  18. # thru 36 through sh.  When all 36 kits have been run, read README.
  19.  
  20. echo "This is perl 4.0 kit 2 (of 36).  If kit 2 is complete, the line"
  21. echo '"'"End of kit 2 (of 36)"'" will echo at the end.'
  22. echo ""
  23. export PATH || (echo "You didn't use sh, you clunch." ; kill $$)
  24. mkdir  2>/dev/null
  25. echo Extracting perl.man:AA
  26. sed >perl.man:AA <<'!STUFFY!FUNK!' -e 's/X//'
  27. X.rn '' }`
  28. X''' $RCSfile: perl.man,v $$Revision: 4.0.1.1 $$Date: 91/04/11 17:50:44 $
  29. X''' 
  30. X''' $Log:    perl.man,v $
  31. X''' Revision 4.0.1.1  91/04/11  17:50:44  lwall
  32. X''' patch1: fixed some typos
  33. X''' 
  34. X''' Revision 4.0  91/03/20  01:38:08  lwall
  35. X''' 4.0 baseline.
  36. X''' 
  37. X''' 
  38. X.de Sh
  39. X.br
  40. X.ne 5
  41. X.PP
  42. X\fB\\$1\fR
  43. X.PP
  44. X..
  45. X.de Sp
  46. X.if t .sp .5v
  47. X.if n .sp
  48. X..
  49. X.de Ip
  50. X.br
  51. X.ie \\n(.$>=3 .ne \\$3
  52. X.el .ne 3
  53. X.IP "\\$1" \\$2
  54. X..
  55. X'''
  56. X'''     Set up \*(-- to give an unbreakable dash;
  57. X'''     string Tr holds user defined translation string.
  58. X'''     Bell System Logo is used as a dummy character.
  59. X'''
  60. X.tr \(*W-|\(bv\*(Tr
  61. X.ie n \{\
  62. X.ds -- \(*W-
  63. X.if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
  64. X.if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
  65. X.ds L" ""
  66. X.ds R" ""
  67. X.ds L' '
  68. X.ds R' '
  69. X'br\}
  70. X.el\{\
  71. X.ds -- \(em\|
  72. X.tr \*(Tr
  73. X.ds L" ``
  74. X.ds R" ''
  75. X.ds L' `
  76. X.ds R' '
  77. X'br\}
  78. X.TH PERL 1 "\*(RP"
  79. X.UC
  80. X.SH NAME
  81. Xperl \- Practical Extraction and Report Language
  82. X.SH SYNOPSIS
  83. X.B perl
  84. X[options] filename args
  85. X.SH DESCRIPTION
  86. X.I Perl
  87. Xis an interpreted language optimized for scanning arbitrary text files,
  88. Xextracting information from those text files, and printing reports based
  89. Xon that information.
  90. XIt's also a good language for many system management tasks.
  91. XThe language is intended to be practical (easy to use, efficient, complete)
  92. Xrather than beautiful (tiny, elegant, minimal).
  93. XIt combines (in the author's opinion, anyway) some of the best features of C,
  94. X\fIsed\fR, \fIawk\fR, and \fIsh\fR,
  95. Xso people familiar with those languages should have little difficulty with it.
  96. X(Language historians will also note some vestiges of \fIcsh\fR, Pascal, and
  97. Xeven BASIC-PLUS.)
  98. XExpression syntax corresponds quite closely to C expression syntax.
  99. XUnlike most Unix utilities,
  100. X.I perl
  101. Xdoes not arbitrarily limit the size of your data\*(--if you've got
  102. Xthe memory,
  103. X.I perl
  104. Xcan slurp in your whole file as a single string.
  105. XRecursion is of unlimited depth.
  106. XAnd the hash tables used by associative arrays grow as necessary to prevent
  107. Xdegraded performance.
  108. X.I Perl
  109. Xuses sophisticated pattern matching techniques to scan large amounts of
  110. Xdata very quickly.
  111. XAlthough optimized for scanning text,
  112. X.I perl
  113. Xcan also deal with binary data, and can make dbm files look like associative
  114. Xarrays (where dbm is available).
  115. XSetuid
  116. X.I perl
  117. Xscripts are safer than C programs
  118. Xthrough a dataflow tracing mechanism which prevents many stupid security holes.
  119. XIf you have a problem that would ordinarily use \fIsed\fR
  120. Xor \fIawk\fR or \fIsh\fR, but it
  121. Xexceeds their capabilities or must run a little faster,
  122. Xand you don't want to write the silly thing in C, then
  123. X.I perl
  124. Xmay be for you.
  125. XThere are also translators to turn your
  126. X.I sed
  127. Xand
  128. X.I awk
  129. Xscripts into
  130. X.I perl
  131. Xscripts.
  132. XOK, enough hype.
  133. X.PP
  134. XUpon startup,
  135. X.I perl
  136. Xlooks for your script in one of the following places:
  137. X.Ip 1. 4 2
  138. XSpecified line by line via
  139. X.B \-e
  140. Xswitches on the command line.
  141. X.Ip 2. 4 2
  142. XContained in the file specified by the first filename on the command line.
  143. X(Note that systems supporting the #! notation invoke interpreters this way.)
  144. X.Ip 3. 4 2
  145. XPassed in implicitly via standard input.
  146. XThis only works if there are no filename arguments\*(--to pass
  147. Xarguments to a
  148. X.I stdin
  149. Xscript you must explicitly specify a \- for the script name.
  150. X.PP
  151. XAfter locating your script,
  152. X.I perl
  153. Xcompiles it to an internal form.
  154. XIf the script is syntactically correct, it is executed.
  155. X.Sh "Options"
  156. XNote: on first reading this section may not make much sense to you.  It's here
  157. Xat the front for easy reference.
  158. X.PP
  159. XA single-character option may be combined with the following option, if any.
  160. XThis is particularly useful when invoking a script using the #! construct which
  161. Xonly allows one argument.  Example:
  162. X.nf
  163. X
  164. X.ne 2
  165. X    #!/usr/bin/perl \-spi.bak    # same as \-s \-p \-i.bak
  166. X    .\|.\|.
  167. X
  168. X.fi
  169. XOptions include:
  170. X.TP 5
  171. X.BI \-0 digits
  172. Xspecifies the record separator ($/) as an octal number.
  173. XIf there are no digits, the null character is the separator.
  174. XOther switches may precede or follow the digits.
  175. XFor example, if you have a version of
  176. X.I find
  177. Xwhich can print filenames terminated by the null character, you can say this:
  178. X.nf
  179. X
  180. X    find . \-name '*.bak' \-print0 | perl \-n0e unlink
  181. X
  182. X.fi
  183. XThe special value 00 will cause Perl to slurp files in paragraph mode.
  184. XThe value 0777 will cause Perl to slurp files whole since there is no
  185. Xlegal character with that value.
  186. X.TP 5
  187. X.B \-a
  188. Xturns on autosplit mode when used with a
  189. X.B \-n
  190. Xor
  191. X.BR \-p .
  192. XAn implicit split command to the @F array
  193. Xis done as the first thing inside the implicit while loop produced by
  194. Xthe
  195. X.B \-n
  196. Xor
  197. X.BR \-p .
  198. X.nf
  199. X
  200. X    perl \-ane \'print pop(@F), "\en";\'
  201. X
  202. Xis equivalent to
  203. X
  204. X    while (<>) {
  205. X        @F = split(\' \');
  206. X        print pop(@F), "\en";
  207. X    }
  208. X
  209. X.fi
  210. X.TP 5
  211. X.B \-c
  212. Xcauses
  213. X.I perl
  214. Xto check the syntax of the script and then exit without executing it.
  215. X.TP 5
  216. X.BI \-d
  217. Xruns the script under the perl debugger.
  218. XSee the section on Debugging.
  219. X.TP 5
  220. X.BI \-D number
  221. Xsets debugging flags.
  222. XTo watch how it executes your script, use
  223. X.BR \-D14 .
  224. X(This only works if debugging is compiled into your
  225. X.IR perl .)
  226. XAnother nice value is \-D1024, which lists your compiled syntax tree.
  227. XAnd \-D512 displays compiled regular expressions.
  228. X.TP 5
  229. X.BI \-e " commandline"
  230. Xmay be used to enter one line of script.
  231. XMultiple
  232. X.B \-e
  233. Xcommands may be given to build up a multi-line script.
  234. XIf
  235. X.B \-e
  236. Xis given,
  237. X.I perl
  238. Xwill not look for a script filename in the argument list.
  239. X.TP 5
  240. X.BI \-i extension
  241. Xspecifies that files processed by the <> construct are to be edited
  242. Xin-place.
  243. XIt does this by renaming the input file, opening the output file by the
  244. Xsame name, and selecting that output file as the default for print statements.
  245. XThe extension, if supplied, is added to the name of the
  246. Xold file to make a backup copy.
  247. XIf no extension is supplied, no backup is made.
  248. XSaying \*(L"perl \-p \-i.bak \-e "s/foo/bar/;" .\|.\|. \*(R" is the same as using
  249. Xthe script:
  250. X.nf
  251. X
  252. X.ne 2
  253. X    #!/usr/bin/perl \-pi.bak
  254. X    s/foo/bar/;
  255. X
  256. Xwhich is equivalent to
  257. X
  258. X.ne 14
  259. X    #!/usr/bin/perl
  260. X    while (<>) {
  261. X        if ($ARGV ne $oldargv) {
  262. X            rename($ARGV, $ARGV . \'.bak\');
  263. X            open(ARGVOUT, ">$ARGV");
  264. X            select(ARGVOUT);
  265. X            $oldargv = $ARGV;
  266. X        }
  267. X        s/foo/bar/;
  268. X    }
  269. X    continue {
  270. X        print;    # this prints to original filename
  271. X    }
  272. X    select(STDOUT);
  273. X
  274. X.fi
  275. Xexcept that the
  276. X.B \-i
  277. Xform doesn't need to compare $ARGV to $oldargv to know when
  278. Xthe filename has changed.
  279. XIt does, however, use ARGVOUT for the selected filehandle.
  280. XNote that
  281. X.I STDOUT
  282. Xis restored as the default output filehandle after the loop.
  283. X.Sp
  284. XYou can use eof to locate the end of each input file, in case you want
  285. Xto append to each file, or reset line numbering (see example under eof).
  286. X.TP 5
  287. X.BI \-I directory
  288. Xmay be used in conjunction with
  289. X.B \-P
  290. Xto tell the C preprocessor where to look for include files.
  291. XBy default /usr/include and /usr/lib/perl are searched.
  292. X.TP 5
  293. X.BI \-l octnum
  294. Xenables automatic line-ending processing.  It has two effects:
  295. Xfirst, it automatically chops the line terminator when used with
  296. X.B \-n
  297. Xor
  298. X.B \-p ,
  299. Xand second, it assigns $\e to have the value of
  300. X.I octnum
  301. Xso that any print statements will have that line terminator added back on.  If
  302. X.I octnum
  303. Xis omitted, sets $\e to the current value of $/.
  304. XFor instance, to trim lines to 80 columns:
  305. X.nf
  306. X
  307. X    perl -lpe \'substr($_, 80) = ""\'
  308. X
  309. X.fi
  310. XNote that the assignment $\e = $/ is done when the switch is processed,
  311. Xso the input record separator can be different than the output record
  312. Xseparator if the
  313. X.B \-l
  314. Xswitch is followed by a
  315. X.B \-0
  316. Xswitch:
  317. X.nf
  318. X
  319. X    gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
  320. X
  321. X.fi
  322. XThis sets $\e to newline and then sets $/ to the null character.
  323. X.TP 5
  324. X.B \-n
  325. Xcauses
  326. X.I perl
  327. Xto assume the following loop around your script, which makes it iterate
  328. Xover filename arguments somewhat like \*(L"sed \-n\*(R" or \fIawk\fR:
  329. X.nf
  330. X
  331. X.ne 3
  332. X    while (<>) {
  333. X        .\|.\|.        # your script goes here
  334. X    }
  335. X
  336. X.fi
  337. XNote that the lines are not printed by default.
  338. XSee
  339. X.B \-p
  340. Xto have lines printed.
  341. XHere is an efficient way to delete all files older than a week:
  342. X.nf
  343. X
  344. X    find . \-mtime +7 \-print | perl \-nle \'unlink;\'
  345. X
  346. X.fi
  347. XThis is faster than using the \-exec switch of find because you don't have to
  348. Xstart a process on every filename found.
  349. X.TP 5
  350. X.B \-p
  351. Xcauses
  352. X.I perl
  353. Xto assume the following loop around your script, which makes it iterate
  354. Xover filename arguments somewhat like \fIsed\fR:
  355. X.nf
  356. X
  357. X.ne 5
  358. X    while (<>) {
  359. X        .\|.\|.        # your script goes here
  360. X    } continue {
  361. X        print;
  362. X    }
  363. X
  364. X.fi
  365. XNote that the lines are printed automatically.
  366. XTo suppress printing use the
  367. X.B \-n
  368. Xswitch.
  369. XA
  370. X.B \-p
  371. Xoverrides a
  372. X.B \-n
  373. Xswitch.
  374. X.TP 5
  375. X.B \-P
  376. Xcauses your script to be run through the C preprocessor before
  377. Xcompilation by
  378. X.IR perl .
  379. X(Since both comments and cpp directives begin with the # character,
  380. Xyou should avoid starting comments with any words recognized
  381. Xby the C preprocessor such as \*(L"if\*(R", \*(L"else\*(R" or \*(L"define\*(R".)
  382. X.TP 5
  383. X.B \-s
  384. Xenables some rudimentary switch parsing for switches on the command line
  385. Xafter the script name but before any filename arguments (or before a \-\|\-).
  386. XAny switch found there is removed from @ARGV and sets the corresponding variable in the
  387. X.I perl
  388. Xscript.
  389. XThe following script prints \*(L"true\*(R" if and only if the script is
  390. Xinvoked with a \-xyz switch.
  391. X.nf
  392. X
  393. X.ne 2
  394. X    #!/usr/bin/perl \-s
  395. X    if ($xyz) { print "true\en"; }
  396. X
  397. X.fi
  398. X.TP 5
  399. X.B \-S
  400. Xmakes
  401. X.I perl
  402. Xuse the PATH environment variable to search for the script
  403. X(unless the name of the script starts with a slash).
  404. XTypically this is used to emulate #! startup on machines that don't
  405. Xsupport #!, in the following manner:
  406. X.nf
  407. X
  408. X    #!/usr/bin/perl
  409. X    eval "exec /usr/bin/perl \-S $0 $*"
  410. X        if $running_under_some_shell;
  411. X
  412. X.fi
  413. XThe system ignores the first line and feeds the script to /bin/sh,
  414. Xwhich proceeds to try to execute the
  415. X.I perl
  416. Xscript as a shell script.
  417. XThe shell executes the second line as a normal shell command, and thus
  418. Xstarts up the
  419. X.I perl
  420. Xinterpreter.
  421. XOn some systems $0 doesn't always contain the full pathname,
  422. Xso the
  423. X.B \-S
  424. Xtells
  425. X.I perl
  426. Xto search for the script if necessary.
  427. XAfter
  428. X.I perl
  429. Xlocates the script, it parses the lines and ignores them because
  430. Xthe variable $running_under_some_shell is never true.
  431. XA better construct than $* would be ${1+"$@"}, which handles embedded spaces
  432. Xand such in the filenames, but doesn't work if the script is being interpreted
  433. Xby csh.
  434. XIn order to start up sh rather than csh, some systems may have to replace the
  435. X#! line with a line containing just
  436. Xa colon, which will be politely ignored by perl.
  437. XOther systems can't control that, and need a totally devious construct that
  438. Xwill work under any of csh, sh or perl, such as the following:
  439. X.nf
  440. X
  441. X.ne 3
  442. X    eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
  443. X    & eval 'exec /usr/bin/perl -S $0 $argv:q'
  444. X        if 0;
  445. X
  446. X.fi
  447. X.TP 5
  448. X.B \-u
  449. Xcauses
  450. X.I perl
  451. Xto dump core after compiling your script.
  452. XYou can then take this core dump and turn it into an executable file
  453. Xby using the undump program (not supplied).
  454. XThis speeds startup at the expense of some disk space (which you can
  455. Xminimize by stripping the executable).
  456. X(Still, a "hello world" executable comes out to about 200K on my machine.)
  457. XIf you are going to run your executable as a set-id program then you
  458. Xshould probably compile it using taintperl rather than normal perl.
  459. XIf you want to execute a portion of your script before dumping, use the
  460. Xdump operator instead.
  461. XNote: availability of undump is platform specific and may not be available
  462. Xfor a specific port of perl.
  463. X.TP 5
  464. X.B \-U
  465. Xallows
  466. X.I perl
  467. Xto do unsafe operations.
  468. XCurrently the only \*(L"unsafe\*(R" operation is the unlinking of directories while
  469. Xrunning as superuser.
  470. X.TP 5
  471. X.B \-v
  472. Xprints the version and patchlevel of your
  473. X.I perl
  474. Xexecutable.
  475. X.TP 5
  476. X.B \-w
  477. Xprints warnings about identifiers that are mentioned only once, and scalar
  478. Xvariables that are used before being set.
  479. XAlso warns about redefined subroutines, and references to undefined
  480. Xfilehandles or filehandles opened readonly that you are attempting to
  481. Xwrite on.
  482. XAlso warns you if you use == on values that don't look like numbers, and if
  483. Xyour subroutines recurse more than 100 deep.
  484. X.TP 5
  485. X.BI \-x directory
  486. Xtells
  487. X.I perl
  488. Xthat the script is embedded in a message.
  489. XLeading garbage will be discarded until the first line that starts
  490. Xwith #! and contains the string "perl".
  491. XAny meaningful switches on that line will be applied (but only one
  492. Xgroup of switches, as with normal #! processing).
  493. XIf a directory name is specified, Perl will switch to that directory
  494. Xbefore running the script.
  495. XThe
  496. X.B \-x
  497. Xswitch only controls the the disposal of leading garbage.
  498. XThe script must be terminated with __END__ if there is trailing garbage
  499. Xto be ignored (the script can process any or all of the trailing garbage
  500. Xvia the DATA filehandle if desired).
  501. X.Sh "Data Types and Objects"
  502. X.PP
  503. X.I Perl
  504. Xhas three data types: scalars, arrays of scalars, and
  505. Xassociative arrays of scalars.
  506. XNormal arrays are indexed by number, and associative arrays by string.
  507. X.PP
  508. XThe interpretation of operations and values in perl sometimes
  509. Xdepends on the requirements
  510. Xof the context around the operation or value.
  511. XThere are three major contexts: string, numeric and array.
  512. XCertain operations return array values
  513. Xin contexts wanting an array, and scalar values otherwise.
  514. X(If this is true of an operation it will be mentioned in the documentation
  515. Xfor that operation.)
  516. XOperations which return scalars don't care whether the context is looking
  517. Xfor a string or a number, but
  518. Xscalar variables and values are interpreted as strings or numbers
  519. Xas appropriate to the context.
  520. XA scalar is interpreted as TRUE in the boolean sense if it is not the null
  521. Xstring or 0.
  522. XBooleans returned by operators are 1 for true and 0 or \'\' (the null
  523. Xstring) for false.
  524. X.PP
  525. XThere are actually two varieties of null string: defined and undefined.
  526. XUndefined null strings are returned when there is no real value for something,
  527. Xsuch as when there was an error, or at end of file, or when you refer
  528. Xto an uninitialized variable or element of an array.
  529. XAn undefined null string may become defined the first time you access it, but
  530. Xprior to that you can use the defined() operator to determine whether the
  531. Xvalue is defined or not.
  532. X.PP
  533. XReferences to scalar variables always begin with \*(L'$\*(R', even when referring
  534. Xto a scalar that is part of an array.
  535. XThus:
  536. X.nf
  537. X
  538. X.ne 3
  539. X    $days    \h'|2i'# a simple scalar variable
  540. X    $days[28]    \h'|2i'# 29th element of array @days
  541. X    $days{\'Feb\'}\h'|2i'# one value from an associative array
  542. X    $#days    \h'|2i'# last index of array @days
  543. X
  544. Xbut entire arrays or array slices are denoted by \*(L'@\*(R':
  545. X
  546. X    @days    \h'|2i'# ($days[0], $days[1],\|.\|.\|. $days[n])
  547. X    @days[3,4,5]\h'|2i'# same as @days[3.\|.5]
  548. X    @days{'a','c'}\h'|2i'# same as ($days{'a'},$days{'c'})
  549. X
  550. Xand entire associative arrays are denoted by \*(L'%\*(R':
  551. X
  552. X    %days    \h'|2i'# (key1, val1, key2, val2 .\|.\|.)
  553. X.fi
  554. X.PP
  555. XAny of these eight constructs may serve as an lvalue,
  556. Xthat is, may be assigned to.
  557. X(It also turns out that an assignment is itself an lvalue in
  558. Xcertain contexts\*(--see examples under s, tr and chop.)
  559. XAssignment to a scalar evaluates the righthand side in a scalar context,
  560. Xwhile assignment to an array or array slice evaluates the righthand side
  561. Xin an array context.
  562. X.PP
  563. XYou may find the length of array @days by evaluating
  564. X\*(L"$#days\*(R", as in
  565. X.IR csh .
  566. 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.)
  567. XAssigning to $#days changes the length of the array.
  568. XShortening an array by this method does not actually destroy any values.
  569. XLengthening an array that was previously shortened recovers the values that
  570. Xwere in those elements.
  571. XYou can also gain some measure of efficiency by preextending an array that
  572. Xis going to get big.
  573. X(You can also extend an array by assigning to an element that is off the
  574. Xend of the array.
  575. XThis differs from assigning to $#whatever in that intervening values
  576. Xare set to null rather than recovered.)
  577. XYou can truncate an array down to nothing by assigning the null list () to
  578. Xit.
  579. XThe following are exactly equivalent
  580. X.nf
  581. X
  582. X    @whatever = ();
  583. X    $#whatever = $[ \- 1;
  584. X
  585. X.fi
  586. X.PP
  587. XIf you evaluate an array in a scalar context, it returns the length of
  588. Xthe array.
  589. XThe following is always true:
  590. X.nf
  591. X
  592. X    @whatever == $#whatever \- $[ + 1;
  593. X
  594. X.fi
  595. X.PP
  596. XMulti-dimensional arrays are not directly supported, but see the discussion
  597. Xof the $; variable later for a means of emulating multiple subscripts with
  598. Xan associative array.
  599. XYou could also write a subroutine to turn multiple subscripts into a single
  600. Xsubscript.
  601. X.PP
  602. XEvery data type has its own namespace.
  603. XYou can, without fear of conflict, use the same name for a scalar variable,
  604. Xan array, an associative array, a filehandle, a subroutine name, and/or
  605. Xa label.
  606. XSince variable and array references always start with \*(L'$\*(R', \*(L'@\*(R',
  607. Xor \*(L'%\*(R', the \*(L"reserved\*(R" words aren't in fact reserved
  608. Xwith respect to variable names.
  609. X(They ARE reserved with respect to labels and filehandles, however, which
  610. Xdon't have an initial special character.
  611. XHint: you could say open(LOG,\'logfile\') rather than open(log,\'logfile\').
  612. XUsing uppercase filehandles also improves readability and protects you
  613. Xfrom conflict with future reserved words.)
  614. XCase IS significant\*(--\*(L"FOO\*(R", \*(L"Foo\*(R" and \*(L"foo\*(R" are all
  615. Xdifferent names.
  616. XNames which start with a letter may also contain digits and underscores.
  617. XNames which do not start with a letter are limited to one character,
  618. Xe.g. \*(L"$%\*(R" or \*(L"$$\*(R".
  619. X(Most of the one character names have a predefined significance to
  620. X.IR perl .
  621. XMore later.)
  622. X.PP
  623. XNumeric literals are specified in any of the usual floating point or
  624. Xinteger formats:
  625. X.nf
  626. X
  627. X.ne 5
  628. X    12345
  629. X    12345.67
  630. X    .23E-10
  631. X    0xffff    # hex
  632. X    0377    # octal
  633. X
  634. X.fi
  635. XString literals are delimited by either single or double quotes.
  636. XThey work much like shell quotes:
  637. Xdouble-quoted string literals are subject to backslash and variable
  638. Xsubstitution; single-quoted strings are not (except for \e\' and \e\e).
  639. XThe usual backslash rules apply for making characters such as newline, tab,
  640. Xetc., as well as some more exotic forms:
  641. X.nf
  642. X
  643. X    \et        tab
  644. X    \en        newline
  645. X    \er        return
  646. X    \ef        form feed
  647. X    \eb        backspace
  648. X    \ea        alarm (bell)
  649. X    \ee        escape
  650. X    \e033        octal char
  651. X    \ex1b        hex char
  652. X    \ec[        control char
  653. X    \el        lowercase next char
  654. X    \eu        uppercase next char
  655. X    \eL        lowercase till \eE
  656. X    \eU        uppercase till \eE
  657. X    \eE        end case modification
  658. X
  659. X.fi
  660. XYou can also embed newlines directly in your strings, i.e. they can end on
  661. Xa different line than they begin.
  662. XThis is nice, but if you forget your trailing quote, the error will not be
  663. Xreported until
  664. X.I perl
  665. Xfinds another line containing the quote character, which
  666. Xmay be much further on in the script.
  667. XVariable substitution inside strings is limited to scalar variables, normal
  668. Xarray values, and array slices.
  669. X(In other words, identifiers beginning with $ or @, followed by an optional
  670. Xbracketed expression as a subscript.)
  671. XThe following code segment prints out \*(L"The price is $100.\*(R"
  672. X.nf
  673. X
  674. X.ne 2
  675. X    $Price = \'$100\';\h'|3.5i'# not interpreted
  676. X    print "The price is $Price.\e\|n";\h'|3.5i'# interpreted
  677. X
  678. X.fi
  679. XNote that you can put curly brackets around the identifier to delimit it
  680. Xfrom following alphanumerics.
  681. XAlso note that a single quoted string must be separated from a preceding
  682. Xword by a space, since single quote is a valid character in an identifier
  683. X(see Packages).
  684. X.PP
  685. XTwo special literals are __LINE__ and __FILE__, which represent the current
  686. Xline number and filename at that point in your program.
  687. XThey may only be used as separate tokens; they will not be interpolated
  688. Xinto strings.
  689. XIn addition, the token __END__ may be used to indicate the logical end of the
  690. Xscript before the actual end of file.
  691. XAny following text is ignored (but may be read via the DATA filehandle).
  692. XThe two control characters ^D and ^Z are synonyms for __END__.
  693. X.PP
  694. XA word that doesn't have any other interpretation in the grammar will be
  695. Xtreated as if it had single quotes around it.
  696. XFor this purpose, a word consists only of alphanumeric characters and underline,
  697. Xand must start with an alphabetic character.
  698. XAs with filehandles and labels, a bare word that consists entirely of
  699. Xlowercase letters risks conflict with future reserved words, and if you
  700. Xuse the
  701. X.B \-w
  702. Xswitch, Perl will warn you about any such words.
  703. X.PP
  704. XArray values are interpolated into double-quoted strings by joining all the
  705. Xelements of the array with the delimiter specified in the $" variable,
  706. Xspace by default.
  707. X(Since in versions of perl prior to 3.0 the @ character was not a metacharacter
  708. Xin double-quoted strings, the interpolation of @array, $array[EXPR],
  709. X@array[LIST], $array{EXPR}, or @array{LIST} only happens if array is
  710. Xreferenced elsewhere in the program or is predefined.)
  711. XThe following are equivalent:
  712. X.nf
  713. X
  714. X.ne 4
  715. X    $temp = join($",@ARGV);
  716. X    system "echo $temp";
  717. X
  718. X    system "echo @ARGV";
  719. X
  720. X.fi
  721. XWithin search patterns (which also undergo double-quotish substitution)
  722. Xthere is a bad ambiguity:  Is /$foo[bar]/ to be
  723. Xinterpreted as /${foo}[bar]/ (where [bar] is a character class for the
  724. Xregular expression) or as /${foo[bar]}/ (where [bar] is the subscript to
  725. Xarray @foo)?
  726. XIf @foo doesn't otherwise exist, then it's obviously a character class.
  727. XIf @foo exists, perl takes a good guess about [bar], and is almost always right.
  728. XIf it does guess wrong, or if you're just plain paranoid,
  729. Xyou can force the correct interpretation with curly brackets as above.
  730. X.PP
  731. XA line-oriented form of quoting is based on the shell here-is syntax.
  732. XFollowing a << you specify a string to terminate the quoted material, and all lines
  733. Xfollowing the current line down to the terminating string are the value
  734. Xof the item.
  735. XThe terminating string may be either an identifier (a word), or some
  736. Xquoted text.
  737. XIf quoted, the type of quotes you use determines the treatment of the text,
  738. Xjust as in regular quoting.
  739. XAn unquoted identifier works like double quotes.
  740. XThere must be no space between the << and the identifier.
  741. X(If you put a space it will be treated as a null identifier, which is
  742. Xvalid, and matches the first blank line\*(--see Merry Christmas example below.)
  743. XThe terminating string must appear by itself (unquoted and with no surrounding
  744. Xwhitespace) on the terminating line.
  745. X.nf
  746. X
  747. X    print <<EOF;        # same as above
  748. XThe price is $Price.
  749. XEOF
  750. X
  751. X    print <<"EOF";        # same as above
  752. XThe price is $Price.
  753. XEOF
  754. X
  755. X    print << x 10;        # null identifier is delimiter
  756. XMerry Christmas!
  757. X
  758. X    print <<`EOC`;        # execute commands
  759. Xecho hi there
  760. Xecho lo there
  761. XEOC
  762. X
  763. X    print <<foo, <<bar;    # you can stack them
  764. XI said foo.
  765. Xfoo
  766. XI said bar.
  767. Xbar
  768. X
  769. X.fi
  770. XArray literals are denoted by separating individual values by commas, and
  771. Xenclosing the list in parentheses:
  772. X.nf
  773. X
  774. X    (LIST)
  775. X
  776. X.fi
  777. XIn a context not requiring an array value, the value of the array literal
  778. Xis the value of the final element, as in the C comma operator.
  779. XFor example,
  780. X.nf
  781. X
  782. X.ne 4
  783. X    @foo = (\'cc\', \'\-E\', $bar);
  784. X
  785. Xassigns the entire array value to array foo, but
  786. X
  787. X    $foo = (\'cc\', \'\-E\', $bar);
  788. X
  789. X.fi
  790. Xassigns the value of variable bar to variable foo.
  791. XNote that the value of an actual array in a scalar context is the length
  792. Xof the array; the following assigns to $foo the value 3:
  793. X.nf
  794. X
  795. X.ne 2
  796. X    @foo = (\'cc\', \'\-E\', $bar);
  797. X    $foo = @foo;        # $foo gets 3
  798. X
  799. X.fi
  800. XYou may have an optional comma before the closing parenthesis of an
  801. Xarray literal, so that you can say:
  802. X.nf
  803. X
  804. X    @foo = (
  805. X    1,
  806. X    2,
  807. X    3,
  808. X    );
  809. X
  810. X.fi
  811. XWhen a LIST is evaluated, each element of the list is evaluated in
  812. Xan array context, and the resulting array value is interpolated into LIST
  813. Xjust as if each individual element were a member of LIST.  Thus arrays
  814. Xlose their identity in a LIST\*(--the list
  815. X
  816. X    (@foo,@bar,&SomeSub)
  817. X
  818. Xcontains all the elements of @foo followed by all the elements of @bar,
  819. Xfollowed by all the elements returned by the subroutine named SomeSub.
  820. X.PP
  821. XA list value may also be subscripted like a normal array.
  822. XExamples:
  823. X.nf
  824. X
  825. X    $time = (stat($file))[8];    # stat returns array value
  826. X    $digit = ('a','b','c','d','e','f')[$digit-10];
  827. X    return (pop(@foo),pop(@foo))[0];
  828. X
  829. X.fi
  830. X.PP
  831. XArray lists may be assigned to if and only if each element of the list
  832. Xis an lvalue:
  833. X.nf
  834. X
  835. X    ($a, $b, $c) = (1, 2, 3);
  836. X
  837. X    ($map{\'red\'}, $map{\'blue\'}, $map{\'green\'}) = (0x00f, 0x0f0, 0xf00);
  838. X
  839. XThe final element may be an array or an associative array:
  840. X
  841. X    ($a, $b, @rest) = split;
  842. X    local($a, $b, %rest) = @_;
  843. X
  844. X.fi
  845. XYou can actually put an array anywhere in the list, but the first array
  846. Xin the list will soak up all the values, and anything after it will get
  847. Xa null value.
  848. XThis may be useful in a local().
  849. X.PP
  850. XAn associative array literal contains pairs of values to be interpreted
  851. Xas a key and a value:
  852. X.nf
  853. X
  854. X.ne 2
  855. X    # same as map assignment above
  856. X    %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  857. X
  858. X.fi
  859. XArray assignment in a scalar context returns the number of elements
  860. Xproduced by the expression on the right side of the assignment:
  861. X.nf
  862. X
  863. X    $x = (($foo,$bar) = (3,2,1));    # set $x to 3, not 2
  864. X
  865. X.fi
  866. X.PP
  867. XThere are several other pseudo-literals that you should know about.
  868. XIf a string is enclosed by backticks (grave accents), it first undergoes
  869. Xvariable substitution just like a double quoted string.
  870. XIt is then interpreted as a command, and the output of that command
  871. Xis the value of the pseudo-literal, like in a shell.
  872. XIn a scalar context, a single string consisting of all the output is
  873. Xreturned.
  874. XIn an array context, an array of values is returned, one for each line
  875. Xof output.
  876. X(You can set $/ to use a different line terminator.)
  877. XThe command is executed each time the pseudo-literal is evaluated.
  878. XThe status value of the command is returned in $? (see Predefined Names
  879. Xfor the interpretation of $?).
  880. XUnlike in \f2csh\f1, no translation is done on the return
  881. Xdata\*(--newlines remain newlines.
  882. XUnlike in any of the shells, single quotes do not hide variable names
  883. Xin the command from interpretation.
  884. XTo pass a $ through to the shell you need to hide it with a backslash.
  885. X.PP
  886. XEvaluating a filehandle in angle brackets yields the next line
  887. Xfrom that file (newline included, so it's never false until EOF, at
  888. Xwhich time an undefined value is returned).
  889. XOrdinarily you must assign that value to a variable,
  890. Xbut there is one situation where an automatic assignment happens.
  891. XIf (and only if) the input symbol is the only thing inside the conditional of a
  892. X.I while
  893. Xloop, the value is
  894. Xautomatically assigned to the variable \*(L"$_\*(R".
  895. X(This may seem like an odd thing to you, but you'll use the construct
  896. Xin almost every
  897. X.I perl
  898. Xscript you write.)
  899. XAnyway, the following lines are equivalent to each other:
  900. X.nf
  901. X
  902. X.ne 5
  903. X    while ($_ = <STDIN>) { print; }
  904. X    while (<STDIN>) { print; }
  905. X    for (\|;\|<STDIN>;\|) { print; }
  906. X    print while $_ = <STDIN>;
  907. X    print while <STDIN>;
  908. X
  909. X.fi
  910. XThe filehandles
  911. X.IR STDIN ,
  912. X.I STDOUT
  913. Xand
  914. X.I STDERR
  915. Xare predefined.
  916. X(The filehandles
  917. X.IR stdin ,
  918. X.I stdout
  919. Xand
  920. X.I stderr
  921. Xwill also work except in packages, where they would be interpreted as
  922. Xlocal identifiers rather than global.)
  923. XAdditional filehandles may be created with the
  924. X.I open
  925. Xfunction.
  926. X.PP
  927. XIf a <FILEHANDLE> is used in a context that is looking for an array, an array
  928. Xconsisting of all the input lines is returned, one line per array element.
  929. XIt's easy to make a LARGE data space this way, so use with care.
  930. X.PP
  931. XThe null filehandle <> is special and can be used to emulate the behavior of
  932. X\fIsed\fR and \fIawk\fR.
  933. XInput from <> comes either from standard input, or from each file listed on
  934. Xthe command line.
  935. XHere's how it works: the first time <> is evaluated, the ARGV array is checked,
  936. Xand if it is null, $ARGV[0] is set to \'-\', which when opened gives you standard
  937. Xinput.
  938. XThe ARGV array is then processed as a list of filenames.
  939. XThe loop
  940. X.nf
  941. X
  942. X.ne 3
  943. X    while (<>) {
  944. X        .\|.\|.            # code for each line
  945. X    }
  946. X
  947. X.ne 10
  948. Xis equivalent to
  949. X
  950. X    unshift(@ARGV, \'\-\') \|if \|$#ARGV < $[;
  951. X    while ($ARGV = shift) {
  952. X        open(ARGV, $ARGV);
  953. X        while (<ARGV>) {
  954. X            .\|.\|.        # code for each line
  955. X        }
  956. X    }
  957. X
  958. X.fi
  959. Xexcept that it isn't as cumbersome to say.
  960. XIt really does shift array ARGV and put the current filename into
  961. Xvariable ARGV.
  962. XIt also uses filehandle ARGV internally.
  963. XYou can modify @ARGV before the first <> as long as you leave the first
  964. Xfilename at the beginning of the array.
  965. XLine numbers ($.) continue as if the input was one big happy file.
  966. X(But see example under eof for how to reset line numbers on each file.)
  967. X.PP
  968. X.ne 5
  969. XIf you want to set @ARGV to your own list of files, go right ahead.
  970. XIf you want to pass switches into your script, you can
  971. Xput a loop on the front like this:
  972. X.nf
  973. X
  974. X.ne 10
  975. X    while ($_ = $ARGV[0], /\|^\-/\|) {
  976. X        shift;
  977. X        last if /\|^\-\|\-$\|/\|;
  978. X        /\|^\-D\|(.*\|)/ \|&& \|($debug = $1);
  979. X        /\|^\-v\|/ \|&& \|$verbose++;
  980. X        .\|.\|.        # other switches
  981. X    }
  982. X    while (<>) {
  983. X        .\|.\|.        # code for each line
  984. X    }
  985. X
  986. X.fi
  987. XThe <> symbol will return FALSE only once.
  988. XIf you call it again after this it will assume you are processing another
  989. X@ARGV list, and if you haven't set @ARGV, will input from
  990. X.IR STDIN .
  991. X.PP
  992. XIf the string inside the angle brackets is a reference to a scalar variable
  993. X(e.g. <$foo>),
  994. Xthen that variable contains the name of the filehandle to input from.
  995. X.PP
  996. XIf the string inside angle brackets is not a filehandle, it is interpreted
  997. Xas a filename pattern to be globbed, and either an array of filenames or the
  998. Xnext filename in the list is returned, depending on context.
  999. XOne level of $ interpretation is done first, but you can't say <$foo>
  1000. Xbecause that's an indirect filehandle as explained in the previous
  1001. Xparagraph.
  1002. XYou could insert curly brackets to force interpretation as a
  1003. Xfilename glob: <${foo}>.
  1004. XExample:
  1005. X.nf
  1006. X
  1007. X.ne 3
  1008. X    while (<*.c>) {
  1009. X        chmod 0644, $_;
  1010. X    }
  1011. X
  1012. Xis equivalent to
  1013. X
  1014. X.ne 5
  1015. X    open(foo, "echo *.c | tr \-s \' \et\er\ef\' \'\e\e012\e\e012\e\e012\e\e012\'|");
  1016. X    while (<foo>) {
  1017. X        chop;
  1018. X        chmod 0644, $_;
  1019. X    }
  1020. X
  1021. X.fi
  1022. XIn fact, it's currently implemented that way.
  1023. X(Which means it will not work on filenames with spaces in them unless
  1024. Xyou have /bin/csh on your machine.)
  1025. XOf course, the shortest way to do the above is:
  1026. X.nf
  1027. X
  1028. X    chmod 0644, <*.c>;
  1029. X
  1030. X.fi
  1031. X.Sh "Syntax"
  1032. X.PP
  1033. XA
  1034. X.I perl
  1035. Xscript consists of a sequence of declarations and commands.
  1036. XThe only things that need to be declared in
  1037. X.I perl
  1038. Xare report formats and subroutines.
  1039. XSee the sections below for more information on those declarations.
  1040. XAll uninitialized user-created objects are assumed to
  1041. Xstart with a null or 0 value until they
  1042. Xare defined by some explicit operation such as assignment.
  1043. XThe sequence of commands is executed just once, unlike in
  1044. X.I sed
  1045. Xand
  1046. X.I awk
  1047. Xscripts, where the sequence of commands is executed for each input line.
  1048. XWhile this means that you must explicitly loop over the lines of your input file
  1049. X(or files), it also means you have much more control over which files and which
  1050. Xlines you look at.
  1051. X(Actually, I'm lying\*(--it is possible to do an implicit loop with either the
  1052. X.B \-n
  1053. Xor
  1054. X.B \-p
  1055. Xswitch.)
  1056. X.PP
  1057. XA declaration can be put anywhere a command can, but has no effect on the
  1058. Xexecution of the primary sequence of commands\*(--declarations all take effect
  1059. Xat compile time.
  1060. XTypically all the declarations are put at the beginning or the end of the script.
  1061. X.PP
  1062. X.I Perl
  1063. Xis, for the most part, a free-form language.
  1064. X(The only exception to this is format declarations, for fairly obvious reasons.)
  1065. XComments are indicated by the # character, and extend to the end of the line.
  1066. XIf you attempt to use /* */ C comments, it will be interpreted either as
  1067. Xdivision or pattern matching, depending on the context.
  1068. XSo don't do that.
  1069. X.Sh "Compound statements"
  1070. XIn
  1071. X.IR perl ,
  1072. Xa sequence of commands may be treated as one command by enclosing it
  1073. Xin curly brackets.
  1074. XWe will call this a BLOCK.
  1075. X.PP
  1076. XThe following compound commands may be used to control flow:
  1077. X.nf
  1078. X
  1079. X.ne 4
  1080. X    if (EXPR) BLOCK
  1081. X    if (EXPR) BLOCK else BLOCK
  1082. X    if (EXPR) BLOCK elsif (EXPR) BLOCK .\|.\|. else BLOCK
  1083. X    LABEL while (EXPR) BLOCK
  1084. X    LABEL while (EXPR) BLOCK continue BLOCK
  1085. X    LABEL for (EXPR; EXPR; EXPR) BLOCK
  1086. X    LABEL foreach VAR (ARRAY) BLOCK
  1087. X    LABEL BLOCK continue BLOCK
  1088. X
  1089. X.fi
  1090. XNote that, unlike C and Pascal, these are defined in terms of BLOCKs, not
  1091. Xstatements.
  1092. XThis means that the curly brackets are \fIrequired\fR\*(--no dangling statements allowed.
  1093. XIf you want to write conditionals without curly brackets there are several
  1094. Xother ways to do it.
  1095. XThe following all do the same thing:
  1096. X.nf
  1097. X
  1098. X.ne 5
  1099. X    if (!open(foo)) { die "Can't open $foo: $!"; }
  1100. X    die "Can't open $foo: $!" unless open(foo);
  1101. X    open(foo) || die "Can't open $foo: $!";    # foo or bust!
  1102. X    open(foo) ? \'hi mom\' : die "Can't open $foo: $!";
  1103. X                # a bit exotic, that last one
  1104. X
  1105. X.fi
  1106. X.PP
  1107. XThe
  1108. X.I if
  1109. Xstatement is straightforward.
  1110. XSince BLOCKs are always bounded by curly brackets, there is never any
  1111. Xambiguity about which
  1112. X.I if
  1113. Xan
  1114. X.I else
  1115. Xgoes with.
  1116. XIf you use
  1117. X.I unless
  1118. Xin place of
  1119. X.IR if ,
  1120. Xthe sense of the test is reversed.
  1121. X.PP
  1122. XThe
  1123. X.I while
  1124. Xstatement executes the block as long as the expression is true
  1125. X(does not evaluate to the null string or 0).
  1126. XThe LABEL is optional, and if present, consists of an identifier followed by
  1127. Xa colon.
  1128. XThe LABEL identifies the loop for the loop control statements
  1129. X.IR next ,
  1130. X.IR last ,
  1131. Xand
  1132. X.I redo
  1133. X(see below).
  1134. XIf there is a
  1135. X.I continue
  1136. XBLOCK, it is always executed just before
  1137. Xthe conditional is about to be evaluated again, similarly to the third part
  1138. Xof a
  1139. X.I for
  1140. Xloop in C.
  1141. XThus it can be used to increment a loop variable, even when the loop has
  1142. Xbeen continued via the
  1143. X.I next
  1144. Xstatement (similar to the C \*(L"continue\*(R" statement).
  1145. X.PP
  1146. XIf the word
  1147. X.I while
  1148. Xis replaced by the word
  1149. X.IR until ,
  1150. Xthe sense of the test is reversed, but the conditional is still tested before
  1151. Xthe first iteration.
  1152. X.PP
  1153. XIn either the
  1154. X.I if
  1155. Xor the
  1156. X.I while
  1157. Xstatement, you may replace \*(L"(EXPR)\*(R" with a BLOCK, and the conditional
  1158. Xis true if the value of the last command in that block is true.
  1159. X.PP
  1160. XThe
  1161. X.I for
  1162. Xloop works exactly like the corresponding
  1163. X.I while
  1164. Xloop:
  1165. X.nf
  1166. X
  1167. X.ne 12
  1168. X    for ($i = 1; $i < 10; $i++) {
  1169. X        .\|.\|.
  1170. X    }
  1171. X
  1172. Xis the same as
  1173. X
  1174. X    $i = 1;
  1175. X    while ($i < 10) {
  1176. X        .\|.\|.
  1177. X    } continue {
  1178. X        $i++;
  1179. X    }
  1180. X.fi
  1181. X.PP
  1182. XThe foreach loop iterates over a normal array value and sets the variable
  1183. XVAR to be each element of the array in turn.
  1184. XThe variable is implicitly local to the loop, and regains its former value
  1185. Xupon exiting the loop.
  1186. XThe \*(L"foreach\*(R" keyword is actually identical to the \*(L"for\*(R" keyword,
  1187. Xso you can use \*(L"foreach\*(R" for readability or \*(L"for\*(R" for brevity.
  1188. XIf VAR is omitted, $_ is set to each value.
  1189. XIf ARRAY is an actual array (as opposed to an expression returning an array
  1190. Xvalue), you can modify each element of the array
  1191. Xby modifying VAR inside the loop.
  1192. XExamples:
  1193. X.nf
  1194. X
  1195. X.ne 5
  1196. X    for (@ary) { s/foo/bar/; }
  1197. X
  1198. X    foreach $elem (@elements) {
  1199. X        $elem *= 2;
  1200. X    }
  1201. X
  1202. X.ne 3
  1203. X    for ((10,9,8,7,6,5,4,3,2,1,\'BOOM\')) {
  1204. X        print $_, "\en"; sleep(1);
  1205. X    }
  1206. X
  1207. X    for (1..15) { print "Merry Christmas\en"; }
  1208. X
  1209. X.ne 3
  1210. X    foreach $item (split(/:[\e\e\en:]*/, $ENV{\'TERMCAP\'})) {
  1211. X        print "Item: $item\en";
  1212. X    }
  1213. X
  1214. X.fi
  1215. X.PP
  1216. XThe BLOCK by itself (labeled or not) is equivalent to a loop that executes
  1217. Xonce.
  1218. XThus you can use any of the loop control statements in it to leave or
  1219. Xrestart the block.
  1220. XThe
  1221. X.I continue
  1222. Xblock is optional.
  1223. XThis construct is particularly nice for doing case structures.
  1224. X.nf
  1225. X
  1226. X.ne 6
  1227. X    foo: {
  1228. X        if (/^abc/) { $abc = 1; last foo; }
  1229. X        if (/^def/) { $def = 1; last foo; }
  1230. X        if (/^xyz/) { $xyz = 1; last foo; }
  1231. X        $nothing = 1;
  1232. X    }
  1233. X
  1234. X.fi
  1235. XThere is no official switch statement in perl, because there
  1236. Xare already several ways to write the equivalent.
  1237. XIn addition to the above, you could write
  1238. X.nf
  1239. X
  1240. X.ne 6
  1241. X    foo: {
  1242. X        $abc = 1, last foo  if /^abc/;
  1243. X        $def = 1, last foo  if /^def/;
  1244. X        $xyz = 1, last foo  if /^xyz/;
  1245. X        $nothing = 1;
  1246. X    }
  1247. X
  1248. Xor
  1249. X
  1250. X.ne 6
  1251. X    foo: {
  1252. X        /^abc/ && do { $abc = 1; last foo; };
  1253. X        /^def/ && do { $def = 1; last foo; };
  1254. X        /^xyz/ && do { $xyz = 1; last foo; };
  1255. X        $nothing = 1;
  1256. X    }
  1257. X
  1258. Xor
  1259. X
  1260. X.ne 6
  1261. X    foo: {
  1262. X        /^abc/ && ($abc = 1, last foo);
  1263. X        /^def/ && ($def = 1, last foo);
  1264. X        /^xyz/ && ($xyz = 1, last foo);
  1265. X        $nothing = 1;
  1266. X    }
  1267. X
  1268. Xor even
  1269. X
  1270. X.ne 8
  1271. X    if (/^abc/)
  1272. X        { $abc = 1; }
  1273. X    elsif (/^def/)
  1274. X        { $def = 1; }
  1275. X    elsif (/^xyz/)
  1276. X        { $xyz = 1; }
  1277. X    else
  1278. X        {$nothing = 1;}
  1279. X
  1280. X.fi
  1281. XAs it happens, these are all optimized internally to a switch structure,
  1282. Xso perl jumps directly to the desired statement, and you needn't worry
  1283. Xabout perl executing a lot of unnecessary statements when you have a string
  1284. Xof 50 elsifs, as long as you are testing the same simple scalar variable
  1285. Xusing ==, eq, or pattern matching as above.
  1286. X(If you're curious as to whether the optimizer has done this for a particular
  1287. Xcase statement, you can use the \-D1024 switch to list the syntax tree
  1288. Xbefore execution.)
  1289. X.Sh "Simple statements"
  1290. XThe only kind of simple statement is an expression evaluated for its side
  1291. Xeffects.
  1292. XEvery expression (simple statement) must be terminated with a semicolon.
  1293. XNote that this is like C, but unlike Pascal (and
  1294. X.IR awk ).
  1295. X.PP
  1296. XAny simple statement may optionally be followed by a
  1297. Xsingle modifier, just before the terminating semicolon.
  1298. XThe possible modifiers are:
  1299. X.nf
  1300. X
  1301. X.ne 4
  1302. X    if EXPR
  1303. X    unless EXPR
  1304. X    while EXPR
  1305. X    until EXPR
  1306. X
  1307. X.fi
  1308. XThe
  1309. X.I if
  1310. Xand
  1311. X.I unless
  1312. Xmodifiers have the expected semantics.
  1313. XThe
  1314. X.I while
  1315. Xand
  1316. X.I until
  1317. Xmodifiers also have the expected semantics (conditional evaluated first),
  1318. Xexcept when applied to a do-BLOCK or a do-SUBROUTINE command,
  1319. Xin which case the block executes once before the conditional is evaluated.
  1320. XThis is so that you can write loops like:
  1321. X.nf
  1322. X
  1323. X.ne 4
  1324. X    do {
  1325. X        $_ = <STDIN>;
  1326. X        .\|.\|.
  1327. X    } until $_ \|eq \|".\|\e\|n";
  1328. X
  1329. X.fi
  1330. X(See the
  1331. X.I do
  1332. Xoperator below.  Note also that the loop control commands described later will
  1333. XNOT work in this construct, since modifiers don't take loop labels.
  1334. XSorry.)
  1335. X.Sh "Expressions"
  1336. XSince
  1337. X.I perl
  1338. Xexpressions work almost exactly like C expressions, only the differences
  1339. Xwill be mentioned here.
  1340. X.PP
  1341. XHere's what
  1342. X.I perl
  1343. Xhas that C doesn't:
  1344. X.Ip ** 8 2
  1345. XThe exponentiation operator.
  1346. X.Ip **= 8
  1347. XThe exponentiation assignment operator.
  1348. X.Ip (\|) 8 3
  1349. XThe null list, used to initialize an array to null.
  1350. X.Ip . 8
  1351. XConcatenation of two strings.
  1352. X.Ip .= 8
  1353. XThe concatenation assignment operator.
  1354. X.Ip eq 8
  1355. XString equality (== is numeric equality).
  1356. XFor a mnemonic just think of \*(L"eq\*(R" as a string.
  1357. X(If you are used to the
  1358. X.I awk
  1359. Xbehavior of using == for either string or numeric equality
  1360. Xbased on the current form of the comparands, beware!
  1361. XYou must be explicit here.)
  1362. X.Ip ne 8
  1363. XString inequality (!= is numeric inequality).
  1364. X.Ip lt 8
  1365. XString less than.
  1366. X.Ip gt 8
  1367. XString greater than.
  1368. X.Ip le 8
  1369. XString less than or equal.
  1370. X.Ip ge 8
  1371. XString greater than or equal.
  1372. X.Ip cmp 8
  1373. XString comparison, returning -1, 0, or 1.
  1374. X.Ip <=> 8
  1375. XNumeric comparison, returning -1, 0, or 1.
  1376. X.Ip =~ 8 2
  1377. XCertain operations search or modify the string \*(L"$_\*(R" by default.
  1378. XThis operator makes that kind of operation work on some other string.
  1379. XThe right argument is a search pattern, substitution, or translation.
  1380. XThe left argument is what is supposed to be searched, substituted, or
  1381. Xtranslated instead of the default \*(L"$_\*(R".
  1382. XThe return value indicates the success of the operation.
  1383. X(If the right argument is an expression other than a search pattern,
  1384. Xsubstitution, or translation, it is interpreted as a search pattern
  1385. Xat run time.
  1386. XThis is less efficient than an explicit search, since the pattern must
  1387. Xbe compiled every time the expression is evaluated.)
  1388. XThe precedence of this operator is lower than unary minus and autoincrement/decrement, but higher than everything else.
  1389. X.Ip !~ 8
  1390. XJust like =~ except the return value is negated.
  1391. X.Ip x 8
  1392. XThe repetition operator.
  1393. XReturns a string consisting of the left operand repeated the
  1394. Xnumber of times specified by the right operand.
  1395. XIn an array context, if the left operand is a list in parens, it repeats
  1396. Xthe list.
  1397. X.nf
  1398. X
  1399. X    print \'\-\' x 80;        # print row of dashes
  1400. X    print \'\-\' x80;        # illegal, x80 is identifier
  1401. X
  1402. X    print "\et" x ($tab/8), \' \' x ($tab%8);    # tab over
  1403. X
  1404. X    @ones = (1) x 80;        # an array of 80 1's
  1405. X    @ones = (5) x @ones;        # set all elements to 5
  1406. X
  1407. X.fi
  1408. X.Ip x= 8
  1409. XThe repetition assignment operator.
  1410. XOnly works on scalars.
  1411. X.Ip .\|. 8
  1412. XThe range operator, which is really two different operators depending
  1413. Xon the context.
  1414. XIn an array context, returns an array of values counting (by ones)
  1415. Xfrom the left value to the right value.
  1416. XThis is useful for writing \*(L"for (1..10)\*(R" loops and for doing
  1417. Xslice operations on arrays.
  1418. X.Sp
  1419. XIn a scalar context, .\|. returns a boolean value.
  1420. XThe operator is bistable, like a flip-flop..
  1421. XEach .\|. operator maintains its own boolean state.
  1422. XIt is false as long as its left operand is false.
  1423. XOnce the left operand is true, the range operator stays true
  1424. Xuntil the right operand is true,
  1425. XAFTER which the range operator becomes false again.
  1426. X(It doesn't become false till the next time the range operator is evaluated.
  1427. XIt can become false on the same evaluation it became true, but it still returns
  1428. Xtrue once.)
  1429. XThe right operand is not evaluated while the operator is in the \*(L"false\*(R" state,
  1430. Xand the left operand is not evaluated while the operator is in the \*(L"true\*(R" state.
  1431. XThe scalar .\|. operator is primarily intended for doing line number ranges
  1432. Xafter
  1433. Xthe fashion of \fIsed\fR or \fIawk\fR.
  1434. XThe precedence is a little lower than || and &&.
  1435. XThe value returned is either the null string for false, or a sequence number
  1436. X(beginning with 1) for true.
  1437. XThe sequence number is reset for each range encountered.
  1438. XThe final sequence number in a range has the string \'E0\' appended to it, which
  1439. Xdoesn't affect its numeric value, but gives you something to search for if you
  1440. Xwant to exclude the endpoint.
  1441. XYou can exclude the beginning point by waiting for the sequence number to be
  1442. Xgreater than 1.
  1443. XIf either operand of scalar .\|. is static, that operand is implicitly compared
  1444. Xto the $. variable, the current line number.
  1445. XExamples:
  1446. X.nf
  1447. X
  1448. X.ne 6
  1449. XAs a scalar operator:
  1450. X    if (101 .\|. 200) { print; }    # print 2nd hundred lines
  1451. X
  1452. X    next line if (1 .\|. /^$/);    # skip header lines
  1453. X
  1454. X    s/^/> / if (/^$/ .\|. eof());    # quote body
  1455. X
  1456. X.ne 4
  1457. XAs an array operator:
  1458. X    for (101 .\|. 200) { print; }    # print $_ 100 times
  1459. X
  1460. X    @foo = @foo[$[ .\|. $#foo];    # an expensive no-op
  1461. X    @foo = @foo[$#foo-4 .\|. $#foo];    # slice last 5 items
  1462. X
  1463. X.fi
  1464. X.Ip \-x 8
  1465. XA file test.
  1466. XThis unary operator takes one argument, either a filename or a filehandle,
  1467. Xand tests the associated file to see if something is true about it.
  1468. XIf the argument is omitted, tests $_, except for \-t, which tests
  1469. X.IR STDIN .
  1470. XIt returns 1 for true and \'\' for false, or the undefined value if the
  1471. Xfile doesn't exist.
  1472. XPrecedence is higher than logical and relational operators, but lower than
  1473. Xarithmetic operators.
  1474. XThe operator may be any of:
  1475. X.nf
  1476. X    \-r    File is readable by effective uid.
  1477. X    \-w    File is writable by effective uid.
  1478. X    \-x    File is executable by effective uid.
  1479. X    \-o    File is owned by effective uid.
  1480. X    \-R    File is readable by real uid.
  1481. X    \-W    File is writable by real uid.
  1482. X    \-X    File is executable by real uid.
  1483. X    \-O    File is owned by real uid.
  1484. X    \-e    File exists.
  1485. X    \-z    File has zero size.
  1486. X    \-s    File has non-zero size (returns size).
  1487. X    \-f    File is a plain file.
  1488. X    \-d    File is a directory.
  1489. X    \-l    File is a symbolic link.
  1490. X    \-p    File is a named pipe (FIFO).
  1491. X    \-S    File is a socket.
  1492. X    \-b    File is a block special file.
  1493. X    \-c    File is a character special file.
  1494. X    \-u    File has setuid bit set.
  1495. X    \-g    File has setgid bit set.
  1496. X    \-k    File has sticky bit set.
  1497. X    \-t    Filehandle is opened to a tty.
  1498. X    \-T    File is a text file.
  1499. X    \-B    File is a binary file (opposite of \-T).
  1500. X    \-M    Age of file in days when script started.
  1501. X    \-A    Same for access time.
  1502. X    \-C    Same for inode change time.
  1503. X
  1504. X.fi
  1505. XThe interpretation of the file permission operators \-r, \-R, \-w, \-W, \-x and \-X
  1506. Xis based solely on the mode of the file and the uids and gids of the user.
  1507. XThere may be other reasons you can't actually read, write or execute the file.
  1508. XAlso note that, for the superuser, \-r, \-R, \-w and \-W always return 1, and 
  1509. X\-x and \-X return 1 if any execute bit is set in the mode.
  1510. XScripts run by the superuser may thus need to do a stat() in order to determine
  1511. Xthe actual mode of the file, or temporarily set the uid to something else.
  1512. X.Sp
  1513. XExample:
  1514. X.nf
  1515. X.ne 7
  1516. X    
  1517. X    while (<>) {
  1518. X        chop;
  1519. X        next unless \-f $_;    # ignore specials
  1520. X        .\|.\|.
  1521. X    }
  1522. X
  1523. X.fi
  1524. XNote that \-s/a/b/ does not do a negated substitution.
  1525. XSaying \-exp($foo) still works as expected, however\*(--only single letters
  1526. Xfollowing a minus are interpreted as file tests.
  1527. X.Sp
  1528. XThe \-T and \-B switches work as follows.
  1529. XThe first block or so of the file is examined for odd characters such as
  1530. Xstrange control codes or metacharacters.
  1531. XIf too many odd characters (>10%) are found, it's a \-B file, otherwise it's a \-T file.
  1532. XAlso, any file containing null in the first block is considered a binary file.
  1533. XIf \-T or \-B is used on a filehandle, the current stdio buffer is examined
  1534. Xrather than the first block.
  1535. XBoth \-T and \-B return TRUE on a null file, or a file at EOF when testing
  1536. Xa filehandle.
  1537. X.PP
  1538. XIf any of the file tests (or either stat operator) are given the special
  1539. Xfilehandle consisting of a solitary underline, then the stat structure
  1540. Xof the previous file test (or stat operator) is used, saving a system
  1541. Xcall.
  1542. X(This doesn't work with \-t, and you need to remember that lstat and -l
  1543. Xwill leave values in the stat structure for the symbolic link, not the
  1544. Xreal file.)
  1545. XExample:
  1546. X.nf
  1547. X
  1548. X    print "Can do.\en" if -r $a || -w _ || -x _;
  1549. X
  1550. X.ne 9
  1551. X    stat($filename);
  1552. X    print "Readable\en" if -r _;
  1553. X    print "Writable\en" if -w _;
  1554. X    print "Executable\en" if -x _;
  1555. X    print "Setuid\en" if -u _;
  1556. X    print "Setgid\en" if -g _;
  1557. X    print "Sticky\en" if -k _;
  1558. X    print "Text\en" if -T _;
  1559. X    print "Binary\en" if -B _;
  1560. X
  1561. X.fi
  1562. X.PP
  1563. XHere is what C has that
  1564. X.I perl
  1565. Xdoesn't:
  1566. X.Ip "unary &" 12
  1567. XAddress-of operator.
  1568. X.Ip "unary *" 12
  1569. XDereference-address operator.
  1570. X.Ip "(TYPE)" 12
  1571. XType casting operator.
  1572. X.PP
  1573. XLike C,
  1574. X.I perl
  1575. Xdoes a certain amount of expression evaluation at compile time, whenever
  1576. Xit determines that all of the arguments to an operator are static and have
  1577. Xno side effects.
  1578. XIn particular, string concatenation happens at compile time between literals that don't do variable substitution.
  1579. XBackslash interpretation also happens at compile time.
  1580. XYou can say
  1581. X.nf
  1582. X
  1583. X.ne 2
  1584. X    \'Now is the time for all\' . "\|\e\|n" .
  1585. X    \'good men to come to.\'
  1586. X
  1587. X.fi
  1588. Xand this all reduces to one string internally.
  1589. X.PP
  1590. XThe autoincrement operator has a little extra built-in magic to it.
  1591. XIf you increment a variable that is numeric, or that has ever been used in
  1592. Xa numeric context, you get a normal increment.
  1593. XIf, however, the variable has only been used in string contexts since it
  1594. Xwas set, and has a value that is not null and matches the
  1595. Xpattern /^[a\-zA\-Z]*[0\-9]*$/, the increment is done
  1596. Xas a string, preserving each character within its range, with carry:
  1597. X.nf
  1598. X
  1599. X    print ++($foo = \'99\');    # prints \*(L'100\*(R'
  1600. X    print ++($foo = \'a0\');    # prints \*(L'a1\*(R'
  1601. X    print ++($foo = \'Az\');    # prints \*(L'Ba\*(R'
  1602. X    print ++($foo = \'zz\');    # prints \*(L'aaa\*(R'
  1603. X
  1604. X.fi
  1605. XThe autodecrement is not magical.
  1606. X.PP
  1607. XThe range operator (in an array context) makes use of the magical
  1608. Xautoincrement algorithm if the minimum and maximum are strings.
  1609. XYou can say
  1610. X
  1611. X    @alphabet = (\'A\' .. \'Z\');
  1612. X
  1613. Xto get all the letters of the alphabet, or
  1614. X
  1615. X    $hexdigit = (0 .. 9, \'a\' .. \'f\')[$num & 15];
  1616. X
  1617. Xto get a hexadecimal digit, or
  1618. X
  1619. X    @z2 = (\'01\' .. \'31\');  print @z2[$mday];
  1620. X
  1621. Xto get dates with leading zeros.
  1622. X(If the final value specified is not in the sequence that the magical increment
  1623. Xwould produce, the sequence goes until the next value would be longer than
  1624. Xthe final value specified.)
  1625. X.PP
  1626. XThe || and && operators differ from C's in that, rather than returning 0 or 1,
  1627. Xthey return the last value evaluated. 
  1628. XThus, a portable way to find out the home directory might be:
  1629. X.nf
  1630. X
  1631. X    $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  1632. X        (getpwuid($<))[7] || die "You're homeless!\en";
  1633. X
  1634. X.fi
  1635. X''' Beginning of part 2
  1636. X''' $RCSfile: perl.man,v $$Revision: 4.0.1.1 $$Date: 91/04/11 17:50:44 $
  1637. X'''
  1638. X''' $Log:    perl.man,v $
  1639. X''' Revision 4.0.1.1  91/04/11  17:50:44  lwall
  1640. X''' patch1: fixed some typos
  1641. X''' 
  1642. X''' Revision 4.0  91/03/20  01:38:08  lwall
  1643. X''' 4.0 baseline.
  1644. X''' 
  1645. X''' Revision 3.0.1.11  91/01/11  18:17:08  lwall
  1646. X''' patch42: fixed some man page entries
  1647. !STUFFY!FUNK!
  1648. echo " "
  1649. echo "End of kit 2 (of 36)"
  1650. cat /dev/null >kit2isdone
  1651. run=''
  1652. config=''
  1653. for iskit in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36; do
  1654.     if test -f kit${iskit}isdone; then
  1655.     run="$run $iskit"
  1656.     else
  1657.     todo="$todo $iskit"
  1658.     fi
  1659. done
  1660. case $todo in
  1661.     '')
  1662.     echo "You have run all your kits.  Please read README and then type Configure."
  1663.     for combo in *:AA; do
  1664.         if test -f "$combo"; then
  1665.         realfile=`basename $combo :AA`
  1666.         cat $realfile:[A-Z][A-Z] >$realfile
  1667.         rm -rf $realfile:[A-Z][A-Z]
  1668.         fi
  1669.     done
  1670.     rm -rf kit*isdone
  1671.     chmod 755 Configure
  1672.     ;;
  1673.     *)  echo "You have run$run."
  1674.     echo "You still need to run$todo."
  1675.     ;;
  1676. esac
  1677. : Someone might mail this, so...
  1678. exit
  1679.  
  1680. exit 0 # Just in case...
  1681. -- 
  1682. Kent Landfield                   INTERNET: kent@sparky.IMD.Sterling.COM
  1683. Sterling Software, IMD           UUCP:     uunet!sparky!kent
  1684. Phone:    (402) 291-8300         FAX:      (402) 291-4362
  1685. Please send comp.sources.misc-related mail to kent@uunet.uu.net.
  1686.