home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume20 / perl3.0 / part06 < prev    next >
Text File  |  1989-10-29  |  50KB  |  1,532 lines

  1. Subject:  v20i089:  Perl, a language with features of C/sed/awk/shell/etc, Part06/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 89
  8. Archive-name: perl3.0/part06
  9.  
  10. #! /bin/sh
  11.  
  12. # Make a new directory for the perl sources, cd to it, and run kits 1
  13. # thru 24 through sh.  When all 24 kits have been run, read README.
  14.  
  15. echo "This is perl 3.0 kit 6 (of 24).  If kit 6 is complete, the line"
  16. echo '"'"End of kit 6 (of 24)"'" will echo at the end.'
  17. echo ""
  18. export PATH || (echo "You didn't use sh, you clunch." ; kill $$)
  19. mkdir eg eg/scan 2>/dev/null
  20. echo Extracting perl.man.4
  21. sed >perl.man.4 <<'!STUFFY!FUNK!' -e 's/X//'
  22. X''' Beginning of part 4
  23. X''' $Header: perl.man.4,v 3.0 89/10/18 15:21:55 lwall Locked $
  24. X'''
  25. X''' $Log:    perl.man.4,v $
  26. X''' Revision 3.0  89/10/18  15:21:55  lwall
  27. X''' 3.0 baseline
  28. X''' 
  29. X.Sh "Precedence"
  30. X.I Perl
  31. Xoperators have the following associativity and precedence:
  32. X.nf
  33. X
  34. Xnonassoc\h'|1i'print printf exec system sort reverse
  35. X\h'1.5i'chmod chown kill unlink utime die return
  36. Xleft\h'|1i',
  37. Xright\h'|1i'= += \-= *= etc.
  38. Xright\h'|1i'?:
  39. Xnonassoc\h'|1i'.\|.
  40. Xleft\h'|1i'||
  41. Xleft\h'|1i'&&
  42. Xleft\h'|1i'| ^
  43. Xleft\h'|1i'&
  44. Xnonassoc\h'|1i'== != eq ne
  45. Xnonassoc\h'|1i'< > <= >= lt gt le ge
  46. Xnonassoc\h'|1i'chdir exit eval reset sleep rand umask
  47. Xnonassoc\h'|1i'\-r \-w \-x etc.
  48. Xleft\h'|1i'<< >>
  49. Xleft\h'|1i'+ \- .
  50. Xleft\h'|1i'* / % x
  51. Xleft\h'|1i'=~ !~ 
  52. Xright\h'|1i'! ~ and unary minus
  53. Xright\h'|1i'**
  54. Xnonassoc\h'|1i'++ \-\|\-
  55. Xleft\h'|1i'\*(L'(\*(R'
  56. X
  57. X.fi
  58. XAs mentioned earlier, if any list operator (print, etc.) or
  59. Xany unary operator (chdir, etc.)
  60. Xis followed by a left parenthesis as the next token on the same line,
  61. Xthe operator and arguments within parentheses are taken to
  62. Xbe of highest precedence, just like a normal function call.
  63. XExamples:
  64. X.nf
  65. X
  66. X    chdir $foo || die;    # (chdir $foo) || die
  67. X    chdir($foo) || die;    # (chdir $foo) || die
  68. X    chdir ($foo) || die;    # (chdir $foo) || die
  69. X    chdir +($foo) || die;    # (chdir $foo) || die
  70. X
  71. Xbut, because * is higher precedence than ||:
  72. X
  73. X    chdir $foo * 20;    # chdir ($foo * 20)
  74. X    chdir($foo) * 20;    # (chdir $foo) * 20
  75. X    chdir ($foo) * 20;    # (chdir $foo) * 20
  76. X    chdir +($foo) * 20;    # chdir ($foo * 20)
  77. X
  78. X    rand 10 * 20;        # rand (10 * 20)
  79. X    rand(10) * 20;        # (rand 10) * 20
  80. X    rand (10) * 20;        # (rand 10) * 20
  81. X    rand +(10) * 20;    # rand (10 * 20)
  82. X
  83. X.fi
  84. XIn the absence of parentheses,
  85. Xthe precedence of list operators such as print, sort or chmod is
  86. Xeither very high or very low depending on whether you look at the left
  87. Xside of operator or the right side of it.
  88. XFor example, in
  89. X.nf
  90. X
  91. X    @ary = (1, 3, sort 4, 2);
  92. X    print @ary;        # prints 1324
  93. X
  94. X.fi
  95. Xthe commas on the right of the sort are evaluated before the sort, but
  96. Xthe commas on the left are evaluated after.
  97. XIn other words, list operators tend to gobble up all the arguments that
  98. Xfollow them, and then act like a simple term with regard to the preceding
  99. Xexpression.
  100. XNote that you have to be careful with parens:
  101. X.nf
  102. X
  103. X.ne 3
  104. X    # These evaluate exit before doing the print:
  105. X    print($foo, exit);    # Obviously not what you want.
  106. X    print $foo, exit;    # Nor is this.
  107. X
  108. X.ne 4
  109. X    # These do the print before evaluating exit:
  110. X    (print $foo), exit;    # This is what you want.
  111. X    print($foo), exit;    # Or this.
  112. X    print ($foo), exit;    # Or even this.
  113. X
  114. XAlso note that
  115. X
  116. X    print ($foo & 255) + 1, "\en";
  117. X
  118. X.fi
  119. Xprobably doesn't do what you expect at first glance.
  120. X.Sh "Subroutines"
  121. XA subroutine may be declared as follows:
  122. X.nf
  123. X
  124. X    sub NAME BLOCK
  125. X
  126. X.fi
  127. X.PP
  128. XAny arguments passed to the routine come in as array @_,
  129. Xthat is ($_[0], $_[1], .\|.\|.).
  130. XThe array @_ is a local array, but its values are references to the
  131. Xactual scalar parameters.
  132. XThe return value of the subroutine is the value of the last expression
  133. Xevaluated, and can be either an array value or a scalar value.
  134. XAlternately, a return statement may be used to specify the returned value and
  135. Xexit the subroutine.
  136. XTo create local variables see the
  137. X.I local
  138. Xoperator.
  139. X.PP
  140. XA subroutine is called using the
  141. X.I do
  142. Xoperator or the & operator.
  143. X.nf
  144. X
  145. X.ne 12
  146. XExample:
  147. X
  148. X    sub MAX {
  149. X        local($max) = pop(@_);
  150. X        foreach $foo (@_) {
  151. X            $max = $foo \|if \|$max < $foo;
  152. X        }
  153. X        $max;
  154. X    }
  155. X
  156. X    .\|.\|.
  157. X    $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  158. X
  159. X.ne 21
  160. XExample:
  161. X
  162. X    # get a line, combining continuation lines
  163. X    #  that start with whitespace
  164. X    sub get_line {
  165. X        $thisline = $lookahead;
  166. X        line: while ($lookahead = <STDIN>) {
  167. X            if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
  168. X                $thisline \|.= \|$lookahead;
  169. X            }
  170. X            else {
  171. X                last line;
  172. X            }
  173. X        }
  174. X        $thisline;
  175. X    }
  176. X
  177. X    $lookahead = <STDIN>;    # get first line
  178. X    while ($_ = do get_line(\|)) {
  179. X        .\|.\|.
  180. X    }
  181. X
  182. X.fi
  183. X.nf
  184. X.ne 6
  185. XUse array assignment to a local list to name your formal arguments:
  186. X
  187. X    sub maybeset {
  188. X        local($key, $value) = @_;
  189. X        $foo{$key} = $value unless $foo{$key};
  190. X    }
  191. X
  192. X.fi
  193. XThis also has the effect of turning call-by-reference into call-by-value,
  194. Xsince the assignment copies the values.
  195. X.Sp
  196. XSubroutines may be called recursively.
  197. XIf a subroutine is called using the & form, the argument list is optional.
  198. XIf omitted, no @_ array is set up for the subroutine; the @_ array at the
  199. Xtime of the call is visible to subroutine instead.
  200. X.nf
  201. X
  202. X    do foo(1,2,3);        # pass three arguments
  203. X    &foo(1,2,3);        # the same
  204. X
  205. X    do foo();        # pass a null list
  206. X    &foo();            # the same
  207. X    &foo;            # pass no arguments--more efficient
  208. X
  209. X.fi
  210. X.Sh "Passing By Reference"
  211. XSometimes you don't want to pass the value of an array to a subroutine but
  212. Xrather the name of it, so that the subroutine can modify the global copy
  213. Xof it rather than working with a local copy.
  214. XIn perl you can refer to all the objects of a particular name by prefixing
  215. Xthe name with a star: *foo.
  216. XWhen evaluated, it produces a scalar value that represents all the objects
  217. Xof that name.
  218. XWhen assigned to within a local() operation, it causes the name mentioned
  219. Xto refer to whatever * value was assigned to it.
  220. XExample:
  221. X.nf
  222. X
  223. X    sub doubleary {
  224. X        local(*someary) = @_;
  225. X        foreach $elem (@someary) {
  226. X        $elem *= 2;
  227. X        }
  228. X    }
  229. X    do doubleary(*foo);
  230. X    do doubleary(*bar);
  231. X
  232. X.fi
  233. XAssignment to *name is currently recommended only inside a local().
  234. XYou can actually assign to *name anywhere, but the previous referent of
  235. X*name may be stranded forever.
  236. XThis may or may not bother you.
  237. X.Sp
  238. XNote that scalars are already passed by reference, so you can modify scalar
  239. Xarguments without using this mechanism by refering explicitly to the $_[nnn]
  240. Xin question.
  241. XYou can modify all the elements of an array by passing all the elements
  242. Xas scalars, but you have to use the * mechanism to push, pop or change the
  243. Xsize of an array.
  244. XThe * mechanism will probably be more efficient in any case.
  245. X.Sp
  246. XSince a *name value contains unprintable binary data, if it is used as
  247. Xan argument in a print, or as a %s argument in a printf or sprintf, it
  248. Xthen has the value '*name', just so it prints out pretty.
  249. X.Sh "Regular Expressions"
  250. XThe patterns used in pattern matching are regular expressions such as
  251. Xthose supplied in the Version 8 regexp routines.
  252. X(In fact, the routines are derived from Henry Spencer's freely redistributable
  253. Xreimplementation of the V8 routines.)
  254. XIn addition, \ew matches an alphanumeric character (including \*(L"_\*(R") and \eW a nonalphanumeric.
  255. XWord boundaries may be matched by \eb, and non-boundaries by \eB.
  256. XA whitespace character is matched by \es, non-whitespace by \eS.
  257. XA numeric character is matched by \ed, non-numeric by \eD.
  258. XYou may use \ew, \es and \ed within character classes.
  259. XAlso, \en, \er, \ef, \et and \eNNN have their normal interpretations.
  260. XWithin character classes \eb represents backspace rather than a word boundary.
  261. XAlternatives may be separated by |.
  262. XThe bracketing construct \|(\ .\|.\|.\ \|) may also be used, in which case \e<digit>
  263. Xmatches the digit'th substring, where digit can range from 1 to 9.
  264. X(Outside of the pattern, always use $ instead of \e in front of the digit.
  265. XThe scope of $<digit> (and $\`, $& and $\')
  266. Xextends to the end of the enclosing BLOCK or eval string, or to
  267. Xthe next pattern match with subexpressions.
  268. XThe \e<digit> notation sometimes works outside the current pattern, but should
  269. Xnot be relied upon.)
  270. X$+ returns whatever the last bracket match matched.
  271. X$& returns the entire matched string.
  272. X($0 normally returns the same thing, but don't depend on it.)
  273. X$\` returns everything before the matched string.
  274. X$\' returns everything after the matched string.
  275. XExamples:
  276. X.nf
  277. X    
  278. X    s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/;    # swap first two words
  279. X
  280. X.ne 5
  281. X    if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
  282. X        $hours = $1;
  283. X        $minutes = $2;
  284. X        $seconds = $3;
  285. X    }
  286. X
  287. X.fi
  288. XBy default, the ^ character matches only the beginning of the string,
  289. Xthe $ character matches only at the end (or before the newline at the end)
  290. Xand
  291. X.I perl
  292. Xdoes certain optimizations with the assumption that the string contains
  293. Xonly one line.
  294. XYou may, however, wish to treat a string as a multi-line buffer, such that
  295. Xthe ^ will match after any newline within the string, and $ will match
  296. Xbefore any newline.
  297. XAt the cost of a little more overhead, you can do this by setting the variable
  298. X$* to 1.
  299. XSetting it back to 0 makes
  300. X.I perl
  301. Xrevert to its old behavior.
  302. X.PP
  303. XTo facilitate multi-line substitutions, the . character never matches a newline
  304. X(even when $* is 0).
  305. XIn particular, the following leaves a newline on the $_ string:
  306. X.nf
  307. X
  308. X    $_ = <STDIN>;
  309. X    s/.*(some_string).*/$1/;
  310. X
  311. XIf the newline is unwanted, try one of
  312. X
  313. X    s/.*(some_string).*\en/$1/;
  314. X    s/.*(some_string)[^\e000]*/$1/;
  315. X    s/.*(some_string)(.|\en)*/$1/;
  316. X    chop; s/.*(some_string).*/$1/;
  317. X    /(some_string)/ && ($_ = $1);
  318. X
  319. X.fi
  320. XAny item of a regular expression may be followed with digits in curly brackets
  321. Xof the form {n,m}, where n gives the minimum number of times to match the item
  322. Xand m gives the maximum.
  323. XThe form {n} is equivalent to {n,n} and matches exactly n times.
  324. XThe form {n,} matches n or more times.
  325. X(If a curly bracket occurs in any other context, it is treated as a regular
  326. Xcharacter.)
  327. XThe * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
  328. Xto {0,1}.
  329. XThere is no limit to the size of n or m, but large numbers will chew up
  330. Xmore memory.
  331. X.Sp
  332. XYou will note that all backslashed metacharacters in
  333. X.I perl
  334. Xare alphanumeric,
  335. Xsuch as \eb, \ew, \en.
  336. XUnlike some other regular expression languages, there are no backslashed
  337. Xsymbols that aren't alphanumeric.
  338. XSo anything that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} is always
  339. Xinterpreted as a literal character, not a metacharacter.
  340. XThis makes it simple to quote a string that you want to use for a pattern
  341. Xbut that you are afraid might contain metacharacters.
  342. XSimply quote all the non-alphanumeric characters:
  343. X.nf
  344. X
  345. X    $pattern =~ s/(\eW)/\e\e$1/g;
  346. X
  347. X.fi
  348. X.Sh "Formats"
  349. XOutput record formats for use with the
  350. X.I write
  351. Xoperator may declared as follows:
  352. X.nf
  353. X
  354. X.ne 3
  355. X    format NAME =
  356. X    FORMLIST
  357. X    .
  358. X
  359. X.fi
  360. XIf name is omitted, format \*(L"STDOUT\*(R" is defined.
  361. XFORMLIST consists of a sequence of lines, each of which may be of one of three
  362. Xtypes:
  363. X.Ip 1. 4
  364. XA comment.
  365. X.Ip 2. 4
  366. XA \*(L"picture\*(R" line giving the format for one output line.
  367. X.Ip 3. 4
  368. XAn argument line supplying values to plug into a picture line.
  369. X.PP
  370. XPicture lines are printed exactly as they look, except for certain fields
  371. Xthat substitute values into the line.
  372. XEach picture field starts with either @ or ^.
  373. XThe @ field (not to be confused with the array marker @) is the normal
  374. Xcase; ^ fields are used
  375. Xto do rudimentary multi-line text block filling.
  376. XThe length of the field is supplied by padding out the field
  377. Xwith multiple <, >, or | characters to specify, respectively, left justification,
  378. Xright justification, or centering.
  379. XIf any of the values supplied for these fields contains a newline, only
  380. Xthe text up to the newline is printed.
  381. XThe special field @* can be used for printing multi-line values.
  382. XIt should appear by itself on a line.
  383. X.PP
  384. XThe values are specified on the following line, in the same order as
  385. Xthe picture fields.
  386. XThe values should be separated by commas.
  387. X.PP
  388. XPicture fields that begin with ^ rather than @ are treated specially.
  389. XThe value supplied must be a scalar variable name which contains a text
  390. Xstring.
  391. X.I Perl
  392. Xputs as much text as it can into the field, and then chops off the front
  393. Xof the string so that the next time the variable is referenced,
  394. Xmore of the text can be printed.
  395. XNormally you would use a sequence of fields in a vertical stack to print
  396. Xout a block of text.
  397. XIf you like, you can end the final field with .\|.\|., which will appear in the
  398. Xoutput if the text was too long to appear in its entirety.
  399. XYou can change which characters are legal to break on by changing the
  400. Xvariable $: to a list of the desired characters.
  401. X.PP
  402. XSince use of ^ fields can produce variable length records if the text to be
  403. Xformatted is short, you can suppress blank lines by putting the tilde (~)
  404. Xcharacter anywhere in the line.
  405. X(Normally you should put it in the front if possible, for visibility.)
  406. XThe tilde will be translated to a space upon output.
  407. XIf you put a second tilde contiguous to the first, the line will be repeated
  408. Xuntil all the fields on the line are exhausted.
  409. X(If you use a field of the @ variety, the expression you supply had better
  410. Xnot give the same value every time forever!)
  411. X.PP
  412. XExamples:
  413. X.nf
  414. X.lg 0
  415. X.cs R 25
  416. X.ft C
  417. X
  418. X.ne 10
  419. X# a report on the /etc/passwd file
  420. Xformat top =
  421. X\&                        Passwd File
  422. XName                Login    Office   Uid   Gid Home
  423. X------------------------------------------------------------------
  424. X\&.
  425. Xformat STDOUT =
  426. X@<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  427. X$name,              $login,  $office,$uid,$gid, $home
  428. X\&.
  429. X
  430. X.ne 29
  431. X# a report from a bug report form
  432. Xformat top =
  433. X\&                        Bug Reports
  434. X@<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  435. X$system,                      $%,         $date
  436. X------------------------------------------------------------------
  437. X\&.
  438. Xformat STDOUT =
  439. XSubject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  440. X\&         $subject
  441. XIndex: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  442. X\&       $index,                       $description
  443. XPriority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  444. X\&          $priority,        $date,   $description
  445. XFrom: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  446. X\&      $from,                         $description
  447. XAssigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  448. X\&             $programmer,            $description
  449. X\&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  450. X\&                                     $description
  451. X\&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  452. X\&                                     $description
  453. X\&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  454. X\&                                     $description
  455. X\&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  456. X\&                                     $description
  457. X\&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  458. X\&                                     $description
  459. X\&.
  460. X
  461. X.ft R
  462. X.cs R
  463. X.lg
  464. X.fi
  465. XIt is possible to intermix prints with writes on the same output channel,
  466. Xbut you'll have to handle $\- (lines left on the page) yourself.
  467. X.PP
  468. XIf you are printing lots of fields that are usually blank, you should consider
  469. Xusing the reset operator between records.
  470. XNot only is it more efficient, but it can prevent the bug of adding another
  471. Xfield and forgetting to zero it.
  472. X.Sh "Interprocess Communication"
  473. XThe IPC facilities of perl are built on the Berkeley socket mechanism.
  474. XIf you don't have sockets, you can ignore this section.
  475. XThe calls have the same names as the corresponding system calls,
  476. Xbut the arguments tend to differ, for two reasons.
  477. XFirst, perl file handles work differently than C file descriptors.
  478. XSecond, perl already knows the length of its strings, so you don't need
  479. Xto pass that information.
  480. XHere is a sample client (untested):
  481. X.nf
  482. X
  483. X    ($them,$port) = @ARGV;
  484. X    $port = 2345 unless $port;
  485. X    $them = 'localhost' unless $them;
  486. X
  487. X    $SIG{'INT'} = 'dokill';
  488. X    sub dokill { kill 9,$child if $child; }
  489. X
  490. X    do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
  491. X
  492. X    $sockaddr = 'S n a4 x8';
  493. X    chop($hostname = `hostname`);
  494. X
  495. X    ($name, $aliases, $proto) = getprotobyname('tcp');
  496. X    ($name, $aliases, $port) = getservbyname($port, 'tcp')
  497. X        unless $port =~ /^\ed+$/;;
  498. X    ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
  499. X    ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
  500. X
  501. X    $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
  502. X    $that = pack($sockaddr, &AF_INET, $port, $thataddr);
  503. X
  504. X    socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  505. X    bind(S, $this) || die "bind: $!";
  506. X    connect(S, $that) || die "connect: $!";
  507. X
  508. X    select(S); $| = 1; select(stdout);
  509. X
  510. X    if ($child = fork) {
  511. X        while (<>) {
  512. X            print S;
  513. X        }
  514. X        sleep 3;
  515. X        do dokill();
  516. X    }
  517. X    else {
  518. X        while (<S>) {
  519. X            print;
  520. X        }
  521. X    }
  522. X
  523. X.fi
  524. XAnd here's a server:
  525. X.nf
  526. X
  527. X    ($port) = @ARGV;
  528. X    $port = 2345 unless $port;
  529. X
  530. X    do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
  531. X
  532. X    $sockaddr = 'S n a4 x8';
  533. X
  534. X    ($name, $aliases, $proto) = getprotobyname('tcp');
  535. X    ($name, $aliases, $port) = getservbyname($port, 'tcp')
  536. X        unless $port =~ /^\ed+$/;;
  537. X
  538. X    $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
  539. X
  540. X    select(NS); $| = 1; select(stdout);
  541. X
  542. X    socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  543. X    bind(S, $this) || die "bind: $!";
  544. X    listen(S, 5) || die "connect: $!";
  545. X
  546. X    select(S); $| = 1; select(stdout);
  547. X
  548. X    for (;;) {
  549. X        print "Listening again\en";
  550. X        ($addr = accept(NS,S)) || die $!;
  551. X        print "accept ok\en";
  552. X
  553. X        ($af,$port,$inetaddr) = unpack($pat,$addr);
  554. X        @inetaddr = unpack('C4',$inetaddr);
  555. X        print "$af $port @inetaddr\en";
  556. X
  557. X        while (<NS>) {
  558. X            print;
  559. X            print NS;
  560. X        }
  561. X    }
  562. X
  563. X.fi
  564. X.Sh "Predefined Names"
  565. XThe following names have special meaning to
  566. X.IR perl .
  567. XI could have used alphabetic symbols for some of these, but I didn't want
  568. Xto take the chance that someone would say reset \*(L"a\-zA\-Z\*(R" and wipe them all
  569. Xout.
  570. XYou'll just have to suffer along with these silly symbols.
  571. XMost of them have reasonable mnemonics, or analogues in one of the shells.
  572. X.Ip $_ 8
  573. XThe default input and pattern-searching space.
  574. XThe following pairs are equivalent:
  575. X.nf
  576. X
  577. X.ne 2
  578. X    while (<>) {\|.\|.\|.    # only equivalent in while!
  579. X    while ($_ = <>) {\|.\|.\|.
  580. X
  581. X.ne 2
  582. X    /\|^Subject:/
  583. X    $_ \|=~ \|/\|^Subject:/
  584. X
  585. X.ne 2
  586. X    y/a\-z/A\-Z/
  587. X    $_ =~ y/a\-z/A\-Z/
  588. X
  589. X.ne 2
  590. X    chop
  591. X    chop($_)
  592. X
  593. X.fi 
  594. X(Mnemonic: underline is understood in certain operations.)
  595. X.Ip $. 8
  596. XThe current input line number of the last filehandle that was read.
  597. XReadonly.
  598. XRemember that only an explicit close on the filehandle resets the line number.
  599. XSince <> never does an explicit close, line numbers increase across ARGV files
  600. X(but see examples under eof).
  601. X(Mnemonic: many programs use . to mean the current line number.)
  602. X.Ip $/ 8
  603. XThe input record separator, newline by default.
  604. XWorks like
  605. X.IR awk 's
  606. XRS variable, including treating blank lines as delimiters
  607. Xif set to the null string.
  608. XIf set to a value longer than one character, only the first character is used.
  609. X(Mnemonic: / is used to delimit line boundaries when quoting poetry.)
  610. X.Ip $, 8
  611. XThe output field separator for the print operator.
  612. XOrdinarily the print operator simply prints out the comma separated fields
  613. Xyou specify.
  614. XIn order to get behavior more like
  615. X.IR awk ,
  616. Xset this variable as you would set
  617. X.IR awk 's
  618. XOFS variable to specify what is printed between fields.
  619. X(Mnemonic: what is printed when there is a , in your print statement.)
  620. X.Ip $"" 8
  621. XThis is like $, except that it applies to array values interpolated into
  622. Xa double-quoted string (or similar interpreted string).
  623. XDefault is a space.
  624. X(Mnemonic: obvious, I think.)
  625. X.Ip $\e 8
  626. XThe output record separator for the print operator.
  627. XOrdinarily the print operator simply prints out the comma separated fields
  628. Xyou specify, with no trailing newline or record separator assumed.
  629. XIn order to get behavior more like
  630. X.IR awk ,
  631. Xset this variable as you would set
  632. X.IR awk 's
  633. XORS variable to specify what is printed at the end of the print.
  634. X(Mnemonic: you set $\e instead of adding \en at the end of the print.
  635. XAlso, it's just like /, but it's what you get \*(L"back\*(R" from
  636. X.IR perl .)
  637. X.Ip $# 8
  638. XThe output format for printed numbers.
  639. XThis variable is a half-hearted attempt to emulate
  640. X.IR awk 's
  641. XOFMT variable.
  642. XThere are times, however, when
  643. X.I awk
  644. Xand
  645. X.I perl
  646. Xhave differing notions of what
  647. Xis in fact numeric.
  648. XAlso, the initial value is %.20g rather than %.6g, so you need to set $#
  649. Xexplicitly to get
  650. X.IR awk 's
  651. Xvalue.
  652. X(Mnemonic: # is the number sign.)
  653. X.Ip $% 8
  654. XThe current page number of the currently selected output channel.
  655. X(Mnemonic: % is page number in nroff.)
  656. X.Ip $= 8
  657. XThe current page length (printable lines) of the currently selected output
  658. Xchannel.
  659. XDefault is 60.
  660. X(Mnemonic: = has horizontal lines.)
  661. X.Ip $\- 8
  662. XThe number of lines left on the page of the currently selected output channel.
  663. X(Mnemonic: lines_on_page \- lines_printed.)
  664. X.Ip $~ 8
  665. XThe name of the current report format for the currently selected output
  666. Xchannel.
  667. X(Mnemonic: brother to $^.)
  668. X.Ip $^ 8
  669. XThe name of the current top-of-page format for the currently selected output
  670. Xchannel.
  671. X(Mnemonic: points to top of page.)
  672. X.Ip $| 8
  673. XIf set to nonzero, forces a flush after every write or print on the currently
  674. Xselected output channel.
  675. XDefault is 0.
  676. XNote that
  677. X.I STDOUT
  678. Xwill typically be line buffered if output is to the
  679. Xterminal and block buffered otherwise.
  680. XSetting this variable is useful primarily when you are outputting to a pipe,
  681. Xsuch as when you are running a
  682. X.I perl
  683. Xscript under rsh and want to see the
  684. Xoutput as it's happening.
  685. X(Mnemonic: when you want your pipes to be piping hot.)
  686. X.Ip $$ 8
  687. XThe process number of the
  688. X.I perl
  689. Xrunning this script.
  690. X(Mnemonic: same as shells.)
  691. X.Ip $? 8
  692. XThe status returned by the last pipe close, backtick (\`\`) command or
  693. X.I system
  694. Xoperator.
  695. XNote that this is the status word returned by the wait() system
  696. Xcall, so the exit value of the subprocess is actually ($? >> 8).
  697. X$? & 255 gives which signal, if any, the process died from, and whether
  698. Xthere was a core dump.
  699. X(Mnemonic: similar to sh and ksh.)
  700. X.Ip $& 8 4
  701. XThe string matched by the last pattern match (not counting any matches hidden
  702. Xwithin a BLOCK or eval enclosed by the current BLOCK).
  703. X(Mnemonic: like & in some editors.)
  704. X.Ip $\` 8 4
  705. XThe string preceding whatever was matched by the last pattern match
  706. X(not counting any matches hidden within a BLOCK or eval enclosed by the current
  707. XBLOCK).
  708. X(Mnemonic: \` often precedes a quoted string.)
  709. X.Ip $\' 8 4
  710. XThe string following whatever was matched by the last pattern match
  711. X(not counting any matches hidden within a BLOCK or eval enclosed by the current
  712. XBLOCK).
  713. X(Mnemonic: \' often follows a quoted string.)
  714. XExample:
  715. X.nf
  716. X
  717. X.ne 3
  718. X    $_ = \'abcdefghi\';
  719. X    /def/;
  720. X    print "$\`:$&:$\'\en";      # prints abc:def:ghi
  721. X
  722. X.fi
  723. X.Ip $+ 8 4
  724. XThe last bracket matched by the last search pattern.
  725. XThis is useful if you don't know which of a set of alternative patterns
  726. Xmatched.
  727. XFor example:
  728. X.nf
  729. X
  730. X    /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
  731. X
  732. X.fi
  733. X(Mnemonic: be positive and forward looking.)
  734. X.Ip $* 8 2
  735. XSet to 1 to do multiline matching within a string, 0 to tell
  736. X.I perl
  737. Xthat it can assume that strings contain a single line, for the purpose
  738. Xof optimizing pattern matches.
  739. XPattern matches on strings containing multiple newlines can produce confusing
  740. Xresults when $* is 0.
  741. XDefault is 0.
  742. X(Mnemonic: * matches multiple things.)
  743. X.Ip $0 8
  744. XContains the name of the file containing the
  745. X.I perl
  746. Xscript being executed.
  747. XThe value should be copied elsewhere before any pattern matching happens, which
  748. Xclobbers $0.
  749. X(Mnemonic: same as sh and ksh.)
  750. X.Ip $<digit> 8
  751. XContains the subpattern from the corresponding set of parentheses in the last
  752. Xpattern matched, not counting patterns matched in nested blocks that have
  753. Xbeen exited already.
  754. X(Mnemonic: like \edigit.)
  755. X.Ip $[ 8 2
  756. XThe index of the first element in an array, and of the first character in
  757. Xa substring.
  758. XDefault is 0, but you could set it to 1 to make
  759. X.I perl
  760. Xbehave more like
  761. X.I awk
  762. X(or Fortran)
  763. Xwhen subscripting and when evaluating the index() and substr() functions.
  764. X(Mnemonic: [ begins subscripts.)
  765. X.Ip $] 8 2
  766. XThe string printed out when you say \*(L"perl -v\*(R".
  767. XIt can be used to determine at the beginning of a script whether the perl
  768. Xinterpreter executing the script is in the right range of versions.
  769. XExample:
  770. X.nf
  771. X
  772. X.ne 5
  773. X    # see if getc is available
  774. X        ($version,$patchlevel) =
  775. X         $] =~ /(\ed+\e.\ed+).*\enPatch level: (\ed+)/;
  776. X        print STDERR "(No filename completion available.)\en"
  777. X         if $version * 1000 + $patchlevel < 2016;
  778. X
  779. X.fi
  780. X(Mnemonic: Is this version of perl in the right bracket?)
  781. X.Ip $; 8 2
  782. XThe subscript separator for multi-dimensional array emulation.
  783. XIf you refer to an associative array element as
  784. X.nf
  785. X    $foo{$a,$b,$c}
  786. X
  787. Xit really means
  788. X
  789. X    $foo{join($;, $a, $b, $c)}
  790. X
  791. XBut don't put
  792. X
  793. X    @foo{$a,$b,$c}        # a slice--note the @
  794. X
  795. Xwhich means
  796. X
  797. X    ($foo{$a},$foo{$b},$foo{$c})
  798. X
  799. X.fi
  800. XDefault is "\e034", the same as SUBSEP in
  801. X.IR awk .
  802. XNote that if your keys contain binary data there might not be any safe
  803. Xvalue for $;.
  804. X(Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
  805. XYeah, I know, it's pretty lame, but $, is already taken for something more
  806. Ximportant.)
  807. X.Ip $! 8 2
  808. XIf used in a numeric context, yields the current value of errno, with all the
  809. Xusual caveats.
  810. XIf used in a string context, yields the corresponding system error string.
  811. XYou can assign to $! in order to set errno
  812. Xif, for instance, you want $! to return the string for error n, or you want
  813. Xto set the exit value for the die operator.
  814. X(Mnemonic: What just went bang?)
  815. X.Ip $@ 8 2
  816. XThe error message from the last eval command.
  817. XIf null, the last eval parsed and executed correctly.
  818. X(Mnemonic: Where was the syntax error \*(L"at\*(R"?)
  819. X.Ip $< 8 2
  820. XThe real uid of this process.
  821. X(Mnemonic: it's the uid you came FROM, if you're running setuid.)
  822. X.Ip $> 8 2
  823. XThe effective uid of this process.
  824. XExample:
  825. X.nf
  826. X
  827. X.ne 2
  828. X    $< = $>;    # set real uid to the effective uid
  829. X    ($<,$>) = ($>,$<);    # swap real and effective uid
  830. X
  831. X.fi
  832. X(Mnemonic: it's the uid you went TO, if you're running setuid.)
  833. XNote: $< and $> can only be swapped on machines supporting setreuid().
  834. X.Ip $( 8 2
  835. XThe real gid of this process.
  836. XIf you are on a machine that supports membership in multiple groups
  837. Xsimultaneously, gives a space separated list of groups you are in.
  838. XThe first number is the one returned by getgid(), and the subsequent ones
  839. Xby getgroups(), one of which may be the same as the first number.
  840. X(Mnemonic: parentheses are used to GROUP things.
  841. XThe real gid is the group you LEFT, if you're running setgid.)
  842. X.Ip $) 8 2
  843. XThe effective gid of this process.
  844. XIf you are on a machine that supports membership in multiple groups
  845. Xsimultaneously, gives a space separated list of groups you are in.
  846. XThe first number is the one returned by getegid(), and the subsequent ones
  847. Xby getgroups(), one of which may be the same as the first number.
  848. X(Mnemonic: parentheses are used to GROUP things.
  849. XThe effective gid is the group that's RIGHT for you, if you're running setgid.)
  850. X.Sp
  851. XNote: $<, $>, $( and $) can only be set on machines that support the
  852. Xcorresponding set[re][ug]id() routine.
  853. X$( and $) can only be swapped on machines supporting setregid().
  854. X.Ip $: 8 2
  855. XThe current set of characters after which a string may be broken to
  856. Xfill continuation fields (starting with ^) in a format.
  857. XDefault is "\ \en-", to break on whitespace or hyphens.
  858. X(Mnemonic: a \*(L"colon\*(R" in poetry is a part of a line.)
  859. X.Ip @ARGV 8 3
  860. XThe array ARGV contains the command line arguments intended for the script.
  861. XNote that $#ARGV is the generally number of arguments minus one, since
  862. X$ARGV[0] is the first argument, NOT the command name.
  863. XSee $0 for the command name.
  864. X.Ip @INC 8 3
  865. XThe array INC contains the list of places to look for
  866. X.I perl
  867. Xscripts to be
  868. Xevaluated by the \*(L"do EXPR\*(R" command.
  869. XIt initially consists of the arguments to any
  870. X.B \-I
  871. Xcommand line switches, followed
  872. Xby the default
  873. X.I perl
  874. Xlibrary, probably \*(L"/usr/local/lib/perl\*(R".
  875. X.Ip $ENV{expr} 8 2
  876. XThe associative array ENV contains your current environment.
  877. XSetting a value in ENV changes the environment for child processes.
  878. X.Ip $SIG{expr} 8 2
  879. XThe associative array SIG is used to set signal handlers for various signals.
  880. XExample:
  881. X.nf
  882. X
  883. X.ne 12
  884. X    sub handler {    # 1st argument is signal name
  885. X        local($sig) = @_;
  886. X        print "Caught a SIG$sig\-\|\-shutting down\en";
  887. X        close(LOG);
  888. X        exit(0);
  889. X    }
  890. X
  891. X    $SIG{\'INT\'} = \'handler\';
  892. X    $SIG{\'QUIT\'} = \'handler\';
  893. X    .\|.\|.
  894. X    $SIG{\'INT\'} = \'DEFAULT\';    # restore default action
  895. X    $SIG{\'QUIT\'} = \'IGNORE\';    # ignore SIGQUIT
  896. X
  897. X.fi
  898. XThe SIG array only contains values for the signals actually set within
  899. Xthe perl script.
  900. X.Sh "Packages"
  901. XPerl provides a mechanism for alternate namespaces to protect packages from
  902. Xstomping on each others variables.
  903. XBy default, a perl script starts compiling into the package known as \*(L"main\*(R".
  904. XBy use of the
  905. X.I package
  906. Xdeclaration, you can switch namespaces.
  907. XThe scope of the package declaration is from the declaration itself to the end
  908. Xof the enclosing block (the same scope as the local() operator).
  909. XTypically it would be the first declaration in a file to be included by
  910. Xthe \*(L"do FILE\*(R" operator.
  911. XYou can switch into a package in more than one place; it merely influences
  912. Xwhich symbol table is used by the compiler for the rest of that block.
  913. XYou can refer to variables in other packages by prefixing the name with
  914. Xthe package name and a single quote.
  915. XIf the package name is null, the \*(L"main\*(R" package as assumed.
  916. XEval'ed strings are compiled in the package in which the eval was compiled
  917. Xin.
  918. X(Assignments to $SIG{}, however, assume the signal handler specified is in the
  919. Xmain package.
  920. XQualify the signal handler name if you wish to have a signal handler in
  921. Xa package.)
  922. XFor an example, examine perldb.pl in the perl library.
  923. XIt initially switches to the DB package so that the debugger doesn't interfere
  924. Xwith variables in the script you are trying to debug.
  925. XAt various points, however, it temporarily switches back to the main package
  926. Xto evaluate various expressions in the context of the main package.
  927. X.PP
  928. XThe symbol table for a package happens to be stored in the associative array
  929. Xof that name prepended with an underscore.
  930. XThe value in each entry of the associative array is
  931. Xwhat you are referring to when you use the *name notation.
  932. XIn fact, the following have the same effect (in package main, anyway),
  933. Xthough the first is more
  934. Xefficient because it does the symbol table lookups at compile time:
  935. X.nf
  936. X
  937. X.ne 2
  938. X    local(*foo) = *bar;
  939. X    local($_main{'foo'}) = $_main{'bar'};
  940. X
  941. X.fi
  942. XYou can use this to print out all the variables in a package, for instance.
  943. XHere is dumpvar.pl from the perl library:
  944. X.nf
  945. X.ne 11
  946. X    package dumpvar;
  947. X
  948. X    sub main'dumpvar {
  949. X    \&    ($package) = @_;
  950. X    \&    local(*stab) = eval("*_$package");
  951. X    \&    while (($key,$val) = each(%stab)) {
  952. X    \&        {
  953. X    \&            local(*entry) = $val;
  954. X    \&            if (defined $entry) {
  955. X    \&                print "\e$$key = '$entry'\en";
  956. X    \&            }
  957. X.ne 7
  958. X    \&            if (defined @entry) {
  959. X    \&                print "\e@$key = (\en";
  960. X    \&                foreach $num ($[ .. $#entry) {
  961. X    \&                    print "  $num\et'",$entry[$num],"'\en";
  962. X    \&                }
  963. X    \&                print ")\en";
  964. X    \&            }
  965. X.ne 10
  966. X    \&            if ($key ne "_$package" && defined %entry) {
  967. X    \&                print "\e%$key = (\en";
  968. X    \&                foreach $key (sort keys(%entry)) {
  969. X    \&                    print "  $key\et'",$entry{$key},"'\en";
  970. X    \&                }
  971. X    \&                print ")\en";
  972. X    \&            }
  973. X    \&        }
  974. X    \&    }
  975. X    }
  976. X
  977. X.fi
  978. XNote that, even though the subroutine is compiled in package dumpvar, the
  979. Xname of the subroutine is qualified so that it's name is inserted into package
  980. X\*(L"main\*(R".
  981. X.Sh "Style"
  982. XEach programmer will, of course, have his or her own preferences in regards
  983. Xto formatting, but there are some general guidelines that will make your
  984. Xprograms easier to read.
  985. X.Ip 1. 4 4
  986. XJust because you CAN do something a particular way doesn't mean that
  987. Xyou SHOULD do it that way.
  988. X.I Perl
  989. Xis designed to give you several ways to do anything, so consider picking
  990. Xthe most readable one.
  991. XFor instance
  992. X
  993. X    open(FOO,$foo) || die "Can't open $foo: $!";
  994. X
  995. Xis better than
  996. X
  997. X    die "Can't open $foo: $!" unless open(FOO,$foo);
  998. X
  999. Xbecause the second way hides the main point of the statement in a
  1000. Xmodifier.
  1001. XOn the other hand
  1002. X
  1003. X    print "Starting analysis\en" if $verbose;
  1004. X
  1005. Xis better than
  1006. X
  1007. X    $verbose && print "Starting analysis\en";
  1008. X
  1009. Xsince the main point isn't whether the user typed -v or not.
  1010. X.Sp
  1011. XSimilarly, just because an operator lets you assume default arguments
  1012. Xdoesn't mean that you have to make use of the defaults.
  1013. XThe defaults are there for lazy systems programmers writing one-shot
  1014. Xprograms.
  1015. XIf you want your program to be readable, consider supplying the argument.
  1016. X.Ip 2. 4 4
  1017. XDon't go through silly contortions to exit a loop at the top or the
  1018. Xbottom, when
  1019. X.I perl
  1020. Xprovides the "last" operator so you can exit in the middle.
  1021. XJust outdent it a little to make it more visible:
  1022. X.nf
  1023. X
  1024. X.ne 7
  1025. X    line:
  1026. X    for (;;) {
  1027. X        statements;
  1028. X    last line if $foo;
  1029. X        next line if /^#/;
  1030. X        statements;
  1031. X    }
  1032. X
  1033. X.fi
  1034. X.Ip 3. 4 4
  1035. XDon't be afraid to use loop labels\*(--they're there to enhance readability as
  1036. Xwell as to allow multi-level loop breaks.
  1037. XSee last example.
  1038. X.Ip 6. 4 4
  1039. XFor portability, when using features that may not be implemented on every
  1040. Xmachine, test the construct in an eval to see if it fails.
  1041. X.Ip 4. 4 4
  1042. XChoose mnemonic indentifiers.
  1043. X.Ip 5. 4 4
  1044. XBe consistent.
  1045. X.Sh "Debugging"
  1046. XIf you invoke
  1047. X.I perl
  1048. Xwith a
  1049. X.B \-d
  1050. Xswitch, your script will be run under a debugging monitor.
  1051. XIt will halt before the first executable statement and ask you for a
  1052. Xcommand, such as:
  1053. X.Ip "h" 12 4
  1054. XPrints out a help message.
  1055. X.Ip "s" 12 4
  1056. XSingle step.
  1057. XExecutes until it reaches the beginning of another statement.
  1058. X.Ip "c" 12 4
  1059. XContinue.
  1060. XExecutes until the next breakpoint is reached.
  1061. X.Ip "<CR>" 12 4
  1062. XRepeat last s or c.
  1063. X.Ip "n" 12 4
  1064. XSingle step around subroutine call.
  1065. X.Ip "l min+incr" 12 4
  1066. XList incr+1 lines starting at min.
  1067. XIf min is omitted, starts where last listing left off.
  1068. XIf incr is omitted, previous value of incr is used.
  1069. X.Ip "l min-max" 12 4
  1070. XList lines in the indicated range.
  1071. X.Ip "l line" 12 4
  1072. XList just the indicated line.
  1073. X.Ip "l" 12 4
  1074. XList incr+1 more lines after last printed line.
  1075. X.Ip "l subname" 12 4
  1076. XList subroutine.
  1077. XIf it's a long subroutine it just lists the beginning.
  1078. XUse \*(L"l\*(R" to list more.
  1079. X.Ip "L" 12 4
  1080. XList lines that have breakpoints or actions.
  1081. X.Ip "t" 12 4
  1082. XToggle trace mode on or off.
  1083. X.Ip "b line" 12 4
  1084. XSet a breakpoint.
  1085. XIf line is omitted, sets a breakpoint on the current line
  1086. Xline that is about to be executed.
  1087. XBreakpoints may only be set on lines that begin an executable statement.
  1088. X.Ip "b subname" 12 4
  1089. XSet breakpoint at first executable line of subroutine.
  1090. X.Ip "S" 12 4
  1091. XLists the names of all subroutines.
  1092. X.Ip "d line" 12 4
  1093. XDelete breakpoint.
  1094. XIf line is omitted, deletes the breakpoint on the current line
  1095. Xline that is about to be executed.
  1096. X.Ip "D" 12 4
  1097. XDelete all breakpoints.
  1098. X.Ip "A" 12 4
  1099. XDelete all line actions.
  1100. X.Ip "V package" 12 4
  1101. XList all variables in package.
  1102. XDefault is main package.
  1103. X.Ip "a line command" 12 4
  1104. XSet an action for line.
  1105. XA multi-line command may be entered by backslashing the newlines.
  1106. X.Ip "< command" 12 4
  1107. XSet an action to happen before every debugger prompt.
  1108. XA multi-line command may be entered by backslashing the newlines.
  1109. X.Ip "> command" 12 4
  1110. XSet an action to happen after the prompt when you've just given a command
  1111. Xto return to executing the script.
  1112. XA multi-line command may be entered by backslashing the newlines.
  1113. X.Ip "! number" 12 4
  1114. XRedo a debugging command.
  1115. XIf number is omitted, redoes the previous command.
  1116. X.Ip "! -number" 12 4
  1117. XRedo the command that was that many commands ago.
  1118. X.Ip "H -number" 12 4
  1119. XDisplay last n commands.
  1120. XOnly commands longer than one character are listed.
  1121. XIf number is omitted, lists them all.
  1122. X.Ip "q or ^D" 12 4
  1123. XQuit.
  1124. X.Ip "command" 12 4
  1125. XExecute command as a perl statement.
  1126. XA missing semicolon will be supplied.
  1127. X.Ip "p expr" 12 4
  1128. XSame as \*(L"print DB'OUT expr\*(R".
  1129. XThe DB'OUT filehandle is opened to /dev/tty, regardless of where STDOUT
  1130. Xmay be redirected to.
  1131. X.PP
  1132. XIf you want to modify the debugger, copy perldb.pl from the perl library
  1133. Xto your current directory and modify it as necessary.
  1134. XYou can do some customization by setting up a .perldb file which contains
  1135. Xinitialization code.
  1136. XFor instance, you could make aliases like these:
  1137. X.nf
  1138. X
  1139. X    $DBalias{'len'} = 's/^len(.*)/p length(\e$1)/';
  1140. X    $DBalias{'stop'} = 's/^stop (at|in)/b/';
  1141. X    $DBalias{'.'} =
  1142. X      's/^./p "\e$DBsub(\e$DBline):\et\e$DBline[\e$DBline]"/';
  1143. X
  1144. X.fi
  1145. X.Sh "Setuid Scripts"
  1146. X.I Perl
  1147. Xis designed to make it easy to write secure setuid and setgid scripts.
  1148. XUnlike shells, which are based on multiple substitution passes on each line
  1149. Xof the script,
  1150. X.I perl
  1151. Xuses a more conventional evaluation scheme with fewer hidden \*(L"gotchas\*(R".
  1152. XAdditionally, since the language has more built-in functionality, it
  1153. Xhas to rely less upon external (and possibly untrustworthy) programs to
  1154. Xaccomplish its purposes.
  1155. X.PP
  1156. XIn an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
  1157. Xinsecure, but this kernel feature can be disabled.
  1158. XIf it is,
  1159. X.I perl
  1160. Xcan emulate the setuid and setgid mechanism when it notices the otherwise
  1161. Xuseless setuid/gid bits on perl scripts.
  1162. XIf the kernel feature isn't disabled,
  1163. X.I perl
  1164. Xwill complain loudly that your setuid script is insecure.
  1165. XYou'll need to either disable the kernel setuid script feature, or put
  1166. Xa C wrapper around the script.
  1167. X.PP
  1168. XWhen perl is executing a setuid script, it takes special precautions to
  1169. Xprevent you from falling into any obvious traps.
  1170. X(In some ways, a perl script is more secure than the corresponding
  1171. XC program.)
  1172. XAny command line argument, environment variable, or input is marked as
  1173. X\*(L"tainted\*(R", and may not be used, directly or indirectly, in any
  1174. Xcommand that invokes a subshell, or in any command that modifies files,
  1175. Xdirectories or processes.
  1176. XAny variable that is set within an expression that has previously referenced
  1177. Xa tainted value also becomes tainted (even if it is logically impossible
  1178. Xfor the tainted value to influence the variable).
  1179. XFor example:
  1180. X.nf
  1181. X
  1182. X.ne 5
  1183. X    $foo = shift;            # $foo is tainted
  1184. X    $bar = $foo,\'bar\';        # $bar is also tainted
  1185. X    $xxx = <>;            # Tainted
  1186. X    $path = $ENV{\'PATH\'};    # Tainted, but see below
  1187. X    $abc = \'abc\';            # Not tainted
  1188. X
  1189. X.ne 4
  1190. X    system "echo $foo";        # Insecure
  1191. X    system "echo", $foo;    # Secure (doesn't use sh)
  1192. X    system "echo $bar";        # Insecure
  1193. X    system "echo $abc";        # Insecure until PATH set
  1194. X
  1195. X.ne 5
  1196. X    $ENV{\'PATH\'} = \'/bin:/usr/bin\';
  1197. X    $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
  1198. X
  1199. X    $path = $ENV{\'PATH\'};    # Not tainted
  1200. X    system "echo $abc";        # Is secure now!
  1201. X
  1202. X.ne 5
  1203. X    open(FOO,"$foo");        # OK
  1204. X    open(FOO,">$foo");         # Not OK
  1205. X
  1206. X    open(FOO,"echo $foo|");    # Not OK, but...
  1207. X    open(FOO,"-|") || exec \'echo\', $foo;    # OK
  1208. X
  1209. X    $zzz = `echo $foo`;        # Insecure, zzz tainted
  1210. X
  1211. X    unlink $abc,$foo;        # Insecure
  1212. X    umask $foo;            # Insecure
  1213. X
  1214. X.ne 3
  1215. X    exec "echo $foo";        # Insecure
  1216. X    exec "echo", $foo;        # Secure (doesn't use sh)
  1217. X    exec "sh", \'-c\', $foo;    # Considered secure, alas
  1218. X
  1219. X.fi
  1220. XThe taintedness is associated with each scalar value, so some elements
  1221. Xof an array can be tainted, and others not.
  1222. X.PP
  1223. XIf you try to do something insecure, you will get a fatal error saying 
  1224. Xsomething like \*(L"Insecure dependency\*(R" or \*(L"Insecure PATH\*(R".
  1225. XNote that you can still write an insecure system call or exec,
  1226. Xbut only by explicity doing something like the last example above.
  1227. XYou can also bypass the tainting mechanism by referencing
  1228. Xsubpatterns\*(--\c
  1229. X.I perl
  1230. Xpresumes that if you reference a substring using $1, $2, etc, you knew
  1231. Xwhat you were doing when you wrote the pattern:
  1232. X.nf
  1233. X
  1234. X    $ARGV[0] =~ /^\-P(\ew+)$/;
  1235. X    $printer = $1;        # Not tainted
  1236. X
  1237. X.fi
  1238. XThis is fairly secure since \ew+ doesn't match shell metacharacters.
  1239. XUse of .+ would have been insecure, but
  1240. X.I perl
  1241. Xdoesn't check for that, so you must be careful with your patterns.
  1242. XThis is the ONLY mechanism for untainting user supplied filenames if you
  1243. Xwant to do file operations on them (unless you make $> equal to $<).
  1244. X.PP
  1245. XIt's also possible to get into trouble with other operations that don't care
  1246. Xwhether they use tainted values.
  1247. XMake judicious use of the file tests in dealing with any user-supplied
  1248. Xfilenames.
  1249. XWhen possible, do opens and such after setting $> = $<.
  1250. X.I Perl
  1251. Xdoesn't prevent you from opening tainted filenames for reading, so be
  1252. Xcareful what you print out.
  1253. XThe tainting mechanism is intended to prevent stupid mistakes, not to remove
  1254. Xthe need for thought.
  1255. X.SH ENVIRONMENT
  1256. X.I Perl
  1257. Xuses PATH in executing subprocesses, and in finding the script if \-S
  1258. Xis used.
  1259. XHOME or LOGDIR are used if chdir has no argument.
  1260. X.PP
  1261. XApart from these,
  1262. X.I perl
  1263. Xuses no environment variables, except to make them available
  1264. Xto the script being executed, and to child processes.
  1265. XHowever, scripts running setuid would do well to execute the following lines
  1266. Xbefore doing anything else, just to keep people honest:
  1267. X.nf
  1268. X
  1269. X.ne 3
  1270. X    $ENV{\'PATH\'} = \'/bin:/usr/bin\';    # or whatever you need
  1271. X    $ENV{\'SHELL\'} = \'/bin/sh\' if $ENV{\'SHELL\'} ne \'\';
  1272. X    $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
  1273. X
  1274. X.fi
  1275. X.SH AUTHOR
  1276. XLarry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
  1277. X.SH FILES
  1278. X/tmp/perl\-eXXXXXX    temporary file for
  1279. X.B \-e
  1280. Xcommands.
  1281. X.SH SEE ALSO
  1282. Xa2p    awk to perl translator
  1283. X.br
  1284. Xs2p    sed to perl translator
  1285. X.SH DIAGNOSTICS
  1286. XCompilation errors will tell you the line number of the error, with an
  1287. Xindication of the next token or token type that was to be examined.
  1288. X(In the case of a script passed to
  1289. X.I perl
  1290. Xvia
  1291. X.B \-e
  1292. Xswitches, each
  1293. X.B \-e
  1294. Xis counted as one line.)
  1295. X.PP
  1296. XSetuid scripts have additional constraints that can produce error messages
  1297. Xsuch as \*(L"Insecure dependency\*(R".
  1298. XSee the section on setuid scripts.
  1299. X.SH TRAPS
  1300. XAccustomed
  1301. X.IR awk
  1302. Xusers should take special note of the following:
  1303. X.Ip * 4 2
  1304. XSemicolons are required after all simple statements in
  1305. X.IR perl .
  1306. XNewline
  1307. Xis not a statement delimiter.
  1308. X.Ip * 4 2
  1309. XCurly brackets are required on ifs and whiles.
  1310. X.Ip * 4 2
  1311. XVariables begin with $ or @ in
  1312. X.IR perl .
  1313. X.Ip * 4 2
  1314. XArrays index from 0 unless you set $[.
  1315. XLikewise string positions in substr() and index().
  1316. X.Ip * 4 2
  1317. XYou have to decide whether your array has numeric or string indices.
  1318. X.Ip * 4 2
  1319. XAssociative array values do not spring into existence upon mere reference.
  1320. X.Ip * 4 2
  1321. XYou have to decide whether you want to use string or numeric comparisons.
  1322. X.Ip * 4 2
  1323. XReading an input line does not split it for you.  You get to split it yourself
  1324. Xto an array.
  1325. XAnd the
  1326. X.I split
  1327. Xoperator has different arguments.
  1328. X.Ip * 4 2
  1329. XThe current input line is normally in $_, not $0.
  1330. XIt generally does not have the newline stripped.
  1331. X($0 is initially the name of the program executed, then the last matched
  1332. Xstring.)
  1333. X.Ip * 4 2
  1334. X$<digit> does not refer to fields\*(--it refers to substrings matched by the last
  1335. Xmatch pattern.
  1336. X.Ip * 4 2
  1337. XThe
  1338. X.I print
  1339. Xstatement does not add field and record separators unless you set
  1340. X$, and $\e.
  1341. X.Ip * 4 2
  1342. XYou must open your files before you print to them.
  1343. X.Ip * 4 2
  1344. XThe range operator is \*(L".\|.\*(R", not comma.
  1345. X(The comma operator works as in C.)
  1346. X.Ip * 4 2
  1347. XThe match operator is \*(L"=~\*(R", not \*(L"~\*(R".
  1348. X(\*(L"~\*(R" is the one's complement operator, as in C.)
  1349. X.Ip * 4 2
  1350. XThe exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
  1351. X(\*(L"^\*(R" is the XOR operator, as in C.)
  1352. X.Ip * 4 2
  1353. XThe concatenation operator is \*(L".\*(R", not the null string.
  1354. X(Using the null string would render \*(L"/pat/ /pat/\*(R" unparsable,
  1355. Xsince the third slash would be interpreted as a division operator\*(--the
  1356. Xtokener is in fact slightly context sensitive for operators like /, ?, and <.
  1357. XAnd in fact, . itself can be the beginning of a number.)
  1358. X.Ip * 4 2
  1359. X.IR Next ,
  1360. X.I exit
  1361. Xand
  1362. X.I continue
  1363. Xwork differently.
  1364. X.Ip * 4 2
  1365. XThe following variables work differently
  1366. X.nf
  1367. X
  1368. X      Awk    \h'|2.5i'Perl
  1369. X      ARGC    \h'|2.5i'$#ARGV
  1370. X      ARGV[0]    \h'|2.5i'$0
  1371. X      FILENAME\h'|2.5i'$ARGV
  1372. X      FNR    \h'|2.5i'$. \- something
  1373. X      FS    \h'|2.5i'(whatever you like)
  1374. X      NF    \h'|2.5i'$#Fld, or some such
  1375. X      NR    \h'|2.5i'$.
  1376. X      OFMT    \h'|2.5i'$#
  1377. X      OFS    \h'|2.5i'$,
  1378. X      ORS    \h'|2.5i'$\e
  1379. X      RLENGTH    \h'|2.5i'length($&)
  1380. X      RS    \h'|2.5i'$/
  1381. X      RSTART    \h'|2.5i'length($\`)
  1382. X      SUBSEP    \h'|2.5i'$;
  1383. X
  1384. X.fi
  1385. X.Ip * 4 2
  1386. XWhen in doubt, run the
  1387. X.I awk
  1388. Xconstruct through a2p and see what it gives you.
  1389. X.PP
  1390. XCerebral C programmers should take note of the following:
  1391. X.Ip * 4 2
  1392. XCurly brackets are required on ifs and whiles.
  1393. X.Ip * 4 2
  1394. XYou should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
  1395. X.Ip * 4 2
  1396. X.I Break
  1397. Xand
  1398. X.I continue
  1399. Xbecome
  1400. X.I last
  1401. Xand
  1402. X.IR next ,
  1403. Xrespectively.
  1404. X.Ip * 4 2
  1405. XThere's no switch statement.
  1406. X.Ip * 4 2
  1407. XVariables begin with $ or @ in
  1408. X.IR perl .
  1409. X.Ip * 4 2
  1410. XPrintf does not implement *.
  1411. X.Ip * 4 2
  1412. XComments begin with #, not /*.
  1413. X.Ip * 4 2
  1414. XYou can't take the address of anything.
  1415. X.Ip * 4 2
  1416. XARGV must be capitalized.
  1417. X.Ip * 4 2
  1418. XThe \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
  1419. X.Ip * 4 2
  1420. XSignal handlers deal with signal names, not numbers.
  1421. X.Ip * 4 2
  1422. XYou can't subscript array values, only arrays (no $x = (1,2,3)[2];).
  1423. X.PP
  1424. XSeasoned
  1425. X.I sed
  1426. Xprogrammers should take note of the following:
  1427. X.Ip * 4 2
  1428. XBackreferences in substitutions use $ rather than \e.
  1429. X.Ip * 4 2
  1430. XThe pattern matching metacharacters (, ), and | do not have backslashes in front.
  1431. X.Ip * 4 2
  1432. XThe range operator is .\|. rather than comma.
  1433. X.PP
  1434. XSharp shell programmers should take note of the following:
  1435. X.Ip * 4 2
  1436. XThe backtick operator does variable interpretation without regard to the
  1437. Xpresence of single quotes in the command.
  1438. X.Ip * 4 2
  1439. XThe backtick operator does no translation of the return value, unlike csh.
  1440. X.Ip * 4 2
  1441. XShells (especially csh) do several levels of substitution on each command line.
  1442. X.I Perl
  1443. Xdoes substitution only in certain constructs such as double quotes,
  1444. Xbackticks, angle brackets and search patterns.
  1445. X.Ip * 4 2
  1446. XShells interpret scripts a little bit at a time.
  1447. X.I Perl
  1448. Xcompiles the whole program before executing it.
  1449. X.Ip * 4 2
  1450. XThe arguments are available via @ARGV, not $1, $2, etc.
  1451. X.Ip * 4 2
  1452. XThe environment is not automatically made available as variables.
  1453. X.SH BUGS
  1454. X.PP
  1455. X.I Perl
  1456. Xis at the mercy of your machine's definitions of various operations
  1457. Xsuch as type casting, atof() and sprintf().
  1458. X.PP
  1459. XIf your stdio requires an seek or eof between reads and writes on a particular
  1460. Xstream, so does
  1461. X.IR perl .
  1462. X.PP
  1463. XWhile none of the built-in data types have any arbitrary size limits (apart
  1464. Xfrom memory size), there are still a few arbitrary limits:
  1465. Xa given identifier may not be longer than 255 characters;
  1466. Xsprintf is limited on many machines to 128 characters per field (unless the format
  1467. Xspecifier is exactly %s);
  1468. Xand no component of your PATH may be longer than 255 if you use \-S.
  1469. X.PP
  1470. X.I Perl
  1471. Xactually stands for Pathologically Eclectic Rubbish Lister, but don't tell
  1472. Xanyone I said that.
  1473. X.rn }` ''
  1474. !STUFFY!FUNK!
  1475. echo Extracting eg/scan/scan_passwd
  1476. sed >eg/scan/scan_passwd <<'!STUFFY!FUNK!' -e 's/X//'
  1477. X#!/usr/bin/perl
  1478. X
  1479. X# $Header: scan_passwd,v 3.0 89/10/18 15:15:43 lwall Locked $
  1480. X
  1481. X# This scans passwd file for security holes.
  1482. X
  1483. Xopen(Pass,'/etc/passwd') || die "Can't open passwd file: $!\n";
  1484. X# $dotriv = (`date` =~ /^Mon/);
  1485. X$dotriv = 1;
  1486. X
  1487. Xwhile (<Pass>) {
  1488. X    ($login,$pass,$uid,$gid,$gcos,$home,$shell) = split(/:/);
  1489. X    if ($shell eq '') {
  1490. X    print "Short: $_";
  1491. X    }
  1492. X    next if /^[+]/;
  1493. X    if ($pass eq '') {
  1494. X    if (index(":sync:lpq:+:", ":$login:") < 0) {
  1495. X        print "No pass: $login\t$gcos\n";
  1496. X    }
  1497. X    }
  1498. X    elsif ($dotriv && crypt($login,substr($pass,0,2)) eq $pass) {
  1499. X    print "Trivial: $login\t$gcos\n";
  1500. X    }
  1501. X    if ($uid == 0) {
  1502. X    if ($login !~ /^.?root$/ && $pass ne '*') {
  1503. X        print "Extra root: $_";
  1504. X    }
  1505. X    }
  1506. X}
  1507. !STUFFY!FUNK!
  1508. echo ""
  1509. echo "End of kit 6 (of 24)"
  1510. cat /dev/null >kit6isdone
  1511. run=''
  1512. config=''
  1513. 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
  1514.     if test -f kit${iskit}isdone; then
  1515.     run="$run $iskit"
  1516.     else
  1517.     todo="$todo $iskit"
  1518.     fi
  1519. done
  1520. case $todo in
  1521.     '')
  1522.     echo "You have run all your kits.  Please read README and then type Configure."
  1523.     chmod 755 Configure
  1524.     ;;
  1525.     *)  echo "You have run$run."
  1526.     echo "You still need to run$todo."
  1527.     ;;
  1528. esac
  1529. : Someone might mail this, so...
  1530. exit
  1531.  
  1532.