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