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