1 ''' Beginning of part 4
2 ''' $Header: perl_man.4,v 3.0.1.11 90/10/16 10:04:28 lwall Locked $
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
8 ''' Revision 3.0.1.10 90/08/09 04:47:35 lwall
9 ''' patch19: added require operator
10 ''' patch19: added numeric interpretation of $]
12 ''' Revision 3.0.1.9 90/08/03 11:15:58 lwall
13 ''' patch19: Intermediate diffs for Randal
15 ''' Revision 3.0.1.8 90/03/27 16:19:31 lwall
16 ''' patch16: MSDOS support
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
21 ''' Revision 3.0.1.6 90/03/12 16:54:04 lwall
22 ''' patch13: improved documentation of *name
24 ''' Revision 3.0.1.5 90/02/28 18:01:52 lwall
25 ''' patch9: $0 is now always the command name
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
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 $@
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
39 ''' Revision 3.0.1.1 89/10/26 23:18:43 lwall
40 ''' patch1: documented the desirability of unnecessary parentheses
42 ''' Revision 3.0 89/10/18 15:21:55 lwall
47 operators have the following associativity and precedence:
50 nonassoc\h'|1i'print printf exec system sort reverse
51 \h'1.5i'chmod chown kill unlink utime die return
53 right\h'|1i'= += \-= *= etc.
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.
68 right\h'|1i'! ~ and unary minus
70 nonassoc\h'|1i'++ \-\|\-
71 left\h'|1i'\*(L'(\*(R'
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.
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
87 but, because * is higher precedence than ||:
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)
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)
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.
107 @ary = (1, 3, sort 4, 2);
108 print @ary; # prints 1324
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
116 Note that you have to be careful with parens:
120 # These evaluate exit before doing the print:
121 print($foo, exit); # Obviously not what you want.
122 print $foo, exit; # Nor is this.
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.
132 print ($foo & 255) + 1, "\en";
135 probably doesn't do what you expect at first glance.
137 A subroutine may be declared as follows:
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
152 To create local variables see the
156 A subroutine is called using the
158 operator or the & operator.
165 local($max) = pop(@_);
167 $max = $foo \|if \|$max < $foo;
173 $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
178 # get a line, combining continuation lines
179 # that start with whitespace
181 $thisline = $lookahead;
182 line: while ($lookahead = <STDIN>) {
183 if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
184 $thisline \|.= \|$lookahead;
193 $lookahead = <STDIN>; # get first line
194 while ($_ = do get_line(\|)) {
201 Use array assignment to a local list to name your formal arguments:
204 local($key, $value) = @_;
205 $foo{$key} = $value unless $foo{$key};
209 This also has the effect of turning call-by-reference into call-by-value,
210 since the assignment copies the values.
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.
218 do foo(1,2,3); # pass three arguments
219 &foo(1,2,3); # the same
221 do foo(); # pass a null list
223 &foo; # pass no arguments--more efficient
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.
240 local(*someary) = @_;
241 foreach $elem (@someary) {
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.
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]
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
260 The * mechanism will probably be more efficient in any case.
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.
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
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
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.
299 s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/; # swap first two words
302 if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
309 By default, the ^ character is only guaranteed to match at the beginning
311 the $ character only at the end (or before the newline at the end)
314 does certain optimizations with the assumption that the string contains
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
320 At the cost of a little more overhead, you can do this by setting the variable
322 Setting it back to 0 makes
324 revert to its old behavior.
326 To facilitate multi-line substitutions, the . character never matches a newline
328 In particular, the following leaves a newline on the $_ string:
332 s/.*(some_string).*/$1/;
334 If the newline is unwanted, try one of
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);
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
350 The * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
352 There is no limit to the size of n or m, but large numbers will chew up
355 You will note that all backslashed metacharacters in
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:
368 $pattern =~ s/(\eW)/\e\e$1/g;
372 Output record formats for use with the
374 operator may declared as follows:
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
389 A \*(L"picture\*(R" line giving the format for one output line.
391 An argument line supplying values to plug into a picture line.
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.
409 The values are specified on the following line, in the same order as
411 The values should be separated by commas.
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
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
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.
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!)
444 # a report on the /etc/passwd file
447 Name Login Office Uid Gid Home
448 ------------------------------------------------------------------
451 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
452 $name, $login, $office,$uid,$gid, $home
456 # a report from a bug report form
459 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
461 ------------------------------------------------------------------
464 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 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
476 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
478 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
480 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
482 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<...
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.
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):
508 ($them,$port) = @ARGV;
509 $port = 2345 unless $port;
510 $them = 'localhost' unless $them;
512 $SIG{'INT'} = 'dokill';
513 sub dokill { kill 9,$child if $child; }
515 require 'sys/socket.ph';
517 $sockaddr = 'S n a4 x8';
518 chop($hostname = `hostname`);
520 ($name, $aliases, $proto) = getprotobyname('tcp');
521 ($name, $aliases, $port) = getservbyname($port, 'tcp')
522 unless $port =~ /^\ed+$/;
524 ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
527 ($name, $aliases, $type, $len, $thisaddr) =
528 gethostbyname($hostname);
530 ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
532 $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
533 $that = pack($sockaddr, &AF_INET, $port, $thataddr);
535 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
536 bind(S, $this) || die "bind: $!";
537 connect(S, $that) || die "connect: $!";
539 select(S); $| = 1; select(stdout);
559 $port = 2345 unless $port;
561 require 'sys/socket.ph';
563 $sockaddr = 'S n a4 x8';
565 ($name, $aliases, $proto) = getprotobyname('tcp');
566 ($name, $aliases, $port) = getservbyname($port, 'tcp')
567 unless $port =~ /^\ed+$/;
569 $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
571 select(NS); $| = 1; select(stdout);
573 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
574 bind(S, $this) || die "bind: $!";
575 listen(S, 5) || die "connect: $!";
577 select(S); $| = 1; select(stdout);
580 print "Listening again\en";
581 ($addr = accept(NS,S)) || die $!;
582 print "accept ok\en";
584 ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
585 @inetaddr = unpack('C4',$inetaddr);
586 print "$af $port @inetaddr\en";
595 .Sh "Predefined Names"
596 The following names have special meaning to
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
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.
604 The default input and pattern-searching space.
605 The following pairs are equivalent:
609 while (<>) {\|.\|.\|. # only equivalent in while!
610 while ($_ = <>) {\|.\|.\|.
614 $_ \|=~ \|/\|^Subject:/
625 (Mnemonic: underline is understood in certain operations.)
627 The current input line number of the last filehandle that was read.
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.)
634 The input record separator, newline by default.
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.)
642 The output field separator for the print operator.
643 Ordinarily the print operator simply prints out the comma separated fields
645 In order to get behavior more like
647 set this variable as you would set
649 OFS variable to specify what is printed between fields.
650 (Mnemonic: what is printed when there is a , in your print statement.)
652 This is like $, except that it applies to array values interpolated into
653 a double-quoted string (or similar interpreted string).
655 (Mnemonic: obvious, I think.)
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
662 set this variable as you would set
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
669 The output format for printed numbers.
670 This variable is a half-hearted attempt to emulate
673 There are times, however, when
677 have differing notions of what
679 Also, the initial value is %.20g rather than %.6g, so you need to set $#
683 (Mnemonic: # is the number sign.)
685 The current page number of the currently selected output channel.
686 (Mnemonic: % is page number in nroff.)
688 The current page length (printable lines) of the currently selected output
691 (Mnemonic: = has horizontal lines.)
693 The number of lines left on the page of the currently selected output channel.
694 (Mnemonic: lines_on_page \- lines_printed.)
696 The name of the current report format for the currently selected output
698 (Mnemonic: brother to $^.)
700 The name of the current top-of-page format for the currently selected output
702 (Mnemonic: points to top of page.)
704 If set to nonzero, forces a flush after every write or print on the currently
705 selected output channel.
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
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.)
718 The process number of the
721 (Mnemonic: same as shells.)
723 The status returned by the last pipe close, backtick (\`\`) command or
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.)
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.)
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
739 (Mnemonic: \` often precedes a quoted string.)
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
744 (Mnemonic: \' often follows a quoted string.)
751 print "$\`:$&:$\'\en"; # prints abc:def:ghi
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
761 /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
764 (Mnemonic: be positive and forward looking.)
766 Set to 1 to do multiline matching within a string, 0 to tell
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.
773 (Mnemonic: * matches multiple things.)
775 Contains the name of the file containing the
777 script being executed.
778 (Mnemonic: same as sh and ksh.)
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
783 (Mnemonic: like \edigit.)
785 The index of the first element in an array, and of the first character in
787 Default is 0, but you could set it to 1 to make
792 when subscripting and when evaluating the index() and substr() functions.
793 (Mnemonic: [ begins subscripts.)
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.
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;
809 or, used numerically,
811 warn "No checksumming!\n" if $] < 3.019;
814 (Mnemonic: Is this version of perl in the right bracket?)
816 The subscript separator for multi-dimensional array emulation.
817 If you refer to an associative array element as
823 $foo{join($;, $a, $b, $c)}
827 @foo{$a,$b,$c} # a slice--note the @
831 ($foo{$a},$foo{$b},$foo{$c})
834 Default is "\e034", the same as SUBSEP in
836 Note that if your keys contain binary data there might not be any safe
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
842 If used in a numeric context, yields the current value of errno, with all the
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
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?)
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"?)
858 The real uid of this process.
859 (Mnemonic: it's the uid you came FROM, if you're running setuid.)
861 The effective uid of this process.
866 $< = $>; # set real uid to the effective uid
867 ($<,$>) = ($>,$<); # swap real and effective uid
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().
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.)
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.)
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().
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.)
898 contains the name of the current file when reading from <>.
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.
905 The array INC contains the list of places to look for
908 evaluated by the \*(L"do EXPR\*(R" command or the \*(L"require\*(r" command.
909 It initially consists of the arguments to any
911 command line switches, followed
914 library, probably \*(L"/usr/local/lib/perl\*(R",
915 followed by \*(L".\*(R", to represent the current directory.
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.
924 The associative array ENV contains your current environment.
925 Setting a value in ENV changes the environment for child processes.
927 The associative array SIG is used to set signal handlers for various signals.
932 sub handler { # 1st argument is signal name
934 print "Caught a SIG$sig\-\|\-shutting down\en";
939 $SIG{\'INT\'} = \'handler\';
940 $SIG{\'QUIT\'} = \'handler\';
942 $SIG{\'INT\'} = \'DEFAULT\'; # restore default action
943 $SIG{\'QUIT\'} = \'IGNORE\'; # ignore SIGQUIT
946 The SIG array only contains values for the signals actually set within
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".
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.
965 Only identifiers starting with letters are stored in the packages symbol
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
976 Eval'ed strings are compiled in the package in which the eval was compiled
978 (Assignments to $SIG{}, however, assume the signal handler specified is in the
980 Qualify the signal handler name if you wish to have a signal handler in
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.
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:
999 local($_main{'foo'}) = $_main{'bar'};
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:
1010 \& local(*stab) = eval("*_$package");
1011 \& while (($key,$val) = each(%stab)) {
1013 \& local(*entry) = $val;
1014 \& if (defined $entry) {
1015 \& print "\e$$key = '$entry'\en";
1018 \& if (defined @entry) {
1019 \& print "\e@$key = (\en";
1020 \& foreach $num ($[ .. $#entry) {
1021 \& print " $num\et'",$entry[$num],"'\en";
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";
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
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.
1046 Just because you CAN do something a particular way doesn't mean that
1047 you SHOULD do it that way.
1049 is designed to give you several ways to do anything, so consider picking
1050 the most readable one.
1053 open(FOO,$foo) || die "Can't open $foo: $!";
1057 die "Can't open $foo: $!" unless open(FOO,$foo);
1059 because the second way hides the main point of the statement in a
1063 print "Starting analysis\en" if $verbose;
1067 $verbose && print "Starting analysis\en";
1069 since the main point isn't whether the user typed -v or not.
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
1075 If you want your program to be readable, consider supplying the argument.
1077 Along the same lines, just because you
1079 omit parentheses in many places doesn't mean that you ought to:
1082 return print reverse sort num values array;
1083 return print(reverse(sort num (values(%array))));
1086 When in doubt, parenthesize.
1087 At the very least it will let some poor schmuck bounce on the % key in vi.
1089 Don't go through silly contortions to exit a loop at the top or the
1092 provides the "last" operator so you can exit in the middle.
1093 Just outdent it a little to make it more visible:
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.
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.
1116 Choose mnemonic identifiers.
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
1128 Prints out a help message.
1133 Executes until it reaches the beginning of another statement.
1136 Executes over subroutine calls, until it reaches the beginning of the
1140 Executes statements until it has finished the current subroutine.
1143 Executes until the next breakpoint is reached.
1145 Continue to the specified line.
1146 Inserts a one-time-only breakpoint at the specified line.
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.
1156 List just the indicated line.
1160 List previous window.
1162 List window around line.
1163 .Ip "l subname" 12 4
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.
1172 List lines that have breakpoints or actions.
1174 Lists the names of all subroutines.
1176 Toggle trace mode on or off.
1177 .Ip "b line condition" 12 4
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.
1188 If line is omitted, deletes the breakpoint on the
1189 line that is about to be executed.
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.
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.
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.
1219 Execute command as a perl statement.
1220 A missing semicolon will be supplied.
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.
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:
1234 $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
1235 $DB'alias{'stop'} = 's/^stop (at|in)/b/';
1237 's/^\e./p "\e$DB\e'sub(\e$DB\e'line):\et",\e$DB\e'line[\e$DB\e'line]/';
1240 .Sh "Setuid Scripts"
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
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.
1251 In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
1252 insecure, but this kernel feature can be disabled.
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,
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.
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
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).
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
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
1291 $ENV{\'PATH\'} = \'/bin:/usr/bin\';
1292 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1294 $path = $ENV{\'PATH\'}; # Not tainted
1295 system "echo $abc"; # Is secure now!
1298 open(FOO,"$foo"); # OK
1299 open(FOO,">$foo"); # Not OK
1301 open(FOO,"echo $foo|"); # Not OK, but...
1302 open(FOO,"-|") || exec \'echo\', $foo; # OK
1304 $zzz = `echo $foo`; # Insecure, zzz tainted
1306 unlink $abc,$foo; # Insecure
1307 umask $foo; # Insecure
1310 exec "echo $foo"; # Insecure
1311 exec "echo", $foo; # Secure (doesn't use sh)
1312 exec "sh", \'-c\', $foo; # Considered secure, alas
1315 The taintedness is associated with each scalar value, so some elements
1316 of an array can be tainted, and others not.
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
1325 presumes that if you reference a substring using $1, $2, etc, you knew
1326 what you were doing when you wrote the pattern:
1329 $ARGV[0] =~ /^\-P(\ew+)$/;
1330 $printer = $1; # Not tainted
1333 This is fairly secure since \ew+ doesn't match shell metacharacters.
1334 Use of .+ would have been insecure, but
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 $<).
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
1344 When possible, do opens and such after setting $> = $<.
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.
1352 uses PATH in executing subprocesses, and in finding the script if \-S
1354 HOME or LOGDIR are used if chdir has no argument.
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:
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 \'\';
1371 Larry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
1373 MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk>
1375 /tmp/perl\-eXXXXXX temporary file for
1379 a2p awk to perl translator
1381 s2p sed to perl translator
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
1391 is counted as one line.)
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.
1399 users should take special note of the following:
1401 Semicolons are required after all simple statements in
1404 is not a statement delimiter.
1406 Curly brackets are required on ifs and whiles.
1408 Variables begin with $ or @ in
1411 Arrays index from 0 unless you set $[.
1412 Likewise string positions in substr() and index().
1414 You have to decide whether your array has numeric or string indices.
1416 Associative array values do not spring into existence upon mere reference.
1418 You have to decide whether you want to use string or numeric comparisons.
1420 Reading an input line does not split it for you. You get to split it yourself
1424 operator has different arguments.
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.)
1430 $<digit> does not refer to fields\*(--it refers to substrings matched by the last
1435 statement does not add field and record separators unless you set
1438 You must open your files before you print to them.
1440 The range operator is \*(L".\|.\*(R", not comma.
1441 (The comma operator works as in C.)
1443 The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
1444 (\*(L"~\*(R" is the one's complement operator, as in C.)
1446 The exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
1447 (\*(L"^\*(R" is the XOR operator, as in C.)
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.)
1461 The following variables work differently
1465 ARGC \h'|2.5i'$#ARGV
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
1475 RLENGTH \h'|2.5i'length($&)
1477 RSTART \h'|2.5i'length($\`)
1482 When in doubt, run the
1484 construct through a2p and see what it gives you.
1486 Cerebral C programmers should take note of the following:
1488 Curly brackets are required on ifs and whiles.
1490 You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
1501 There's no switch statement.
1503 Variables begin with $ or @ in
1506 Printf does not implement *.
1508 Comments begin with #, not /*.
1510 You can't take the address of anything.
1512 ARGV must be capitalized.
1514 The \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
1516 Signal handlers deal with signal names, not numbers.
1520 programmers should take note of the following:
1522 Backreferences in substitutions use $ rather than \e.
1524 The pattern matching metacharacters (, ), and | do not have backslashes in front.
1526 The range operator is .\|. rather than comma.
1528 Sharp shell programmers should take note of the following:
1530 The backtick operator does variable interpretation without regard to the
1531 presence of single quotes in the command.
1533 The backtick operator does no translation of the return value, unlike csh.
1535 Shells (especially csh) do several levels of substitution on each command line.
1537 does substitution only in certain constructs such as double quotes,
1538 backticks, angle brackets and search patterns.
1540 Shells interpret scripts a little bit at a time.
1542 compiles the whole program before executing it.
1544 The arguments are available via @ARGV, not $1, $2, etc.
1546 The environment is not automatically made available as variables.
1550 is at the mercy of your machine's definitions of various operations
1551 such as type casting, atof() and sprintf().
1553 If your stdio requires an seek or eof between reads and writes on a particular
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.
1565 actually stands for Pathologically Eclectic Rubbish Lister, but don't tell