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