home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume20 / perl3.0 / part01 next >
Encoding:
Internet Message Format  |  1989-10-29  |  49.1 KB

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