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