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