1 ''' Beginning of part 4
2 ''' $Header: perl_man.4,v 3.0.1.12 90/10/20 02:15:43 lwall Locked $
4 ''' $Log: perl.man.4,v $
5 ''' Revision 3.0.1.12 90/10/20 02:15:43 lwall
6 ''' patch37: patch37: fixed various typos in man page
8 ''' Revision 3.0.1.11 90/10/16 10:04:28 lwall
9 ''' patch29: added @###.## fields to format
11 ''' Revision 3.0.1.10 90/08/09 04:47:35 lwall
12 ''' patch19: added require operator
13 ''' patch19: added numeric interpretation of $]
15 ''' Revision 3.0.1.9 90/08/03 11:15:58 lwall
16 ''' patch19: Intermediate diffs for Randal
18 ''' Revision 3.0.1.8 90/03/27 16:19:31 lwall
19 ''' patch16: MSDOS support
21 ''' Revision 3.0.1.7 90/03/14 12:29:50 lwall
22 ''' patch15: man page falsely states that you can't subscript array values
24 ''' Revision 3.0.1.6 90/03/12 16:54:04 lwall
25 ''' patch13: improved documentation of *name
27 ''' Revision 3.0.1.5 90/02/28 18:01:52 lwall
28 ''' patch9: $0 is now always the command name
30 ''' Revision 3.0.1.4 89/12/21 20:12:39 lwall
31 ''' patch7: documented that package'filehandle works as well as $package'variable
32 ''' patch7: documented which identifiers are always in package main
34 ''' Revision 3.0.1.3 89/11/17 15:32:25 lwall
35 ''' patch5: fixed some manual typos and indent problems
36 ''' patch5: clarified difference between $! and $@
38 ''' Revision 3.0.1.2 89/11/11 04:46:40 lwall
39 ''' patch2: made some line breaks depend on troff vs. nroff
40 ''' patch2: clarified operation of ^ and $ when $* is false
42 ''' Revision 3.0.1.1 89/10/26 23:18:43 lwall
43 ''' patch1: documented the desirability of unnecessary parentheses
45 ''' Revision 3.0 89/10/18 15:21:55 lwall
50 operators have the following associativity and precedence:
53 nonassoc\h'|1i'print printf exec system sort reverse
54 \h'1.5i'chmod chown kill unlink utime die return
56 right\h'|1i'= += \-= *= etc.
63 nonassoc\h'|1i'== != eq ne
64 nonassoc\h'|1i'< > <= >= lt gt le ge
65 nonassoc\h'|1i'chdir exit eval reset sleep rand umask
66 nonassoc\h'|1i'\-r \-w \-x etc.
71 right\h'|1i'! ~ and unary minus
73 nonassoc\h'|1i'++ \-\|\-
74 left\h'|1i'\*(L'(\*(R'
77 As mentioned earlier, if any list operator (print, etc.) or
78 any unary operator (chdir, etc.)
79 is followed by a left parenthesis as the next token on the same line,
80 the operator and arguments within parentheses are taken to
81 be of highest precedence, just like a normal function call.
85 chdir $foo || die;\h'|3i'# (chdir $foo) || die
86 chdir($foo) || die;\h'|3i'# (chdir $foo) || die
87 chdir ($foo) || die;\h'|3i'# (chdir $foo) || die
88 chdir +($foo) || die;\h'|3i'# (chdir $foo) || die
90 but, because * is higher precedence than ||:
92 chdir $foo * 20;\h'|3i'# chdir ($foo * 20)
93 chdir($foo) * 20;\h'|3i'# (chdir $foo) * 20
94 chdir ($foo) * 20;\h'|3i'# (chdir $foo) * 20
95 chdir +($foo) * 20;\h'|3i'# chdir ($foo * 20)
97 rand 10 * 20;\h'|3i'# rand (10 * 20)
98 rand(10) * 20;\h'|3i'# (rand 10) * 20
99 rand (10) * 20;\h'|3i'# (rand 10) * 20
100 rand +(10) * 20;\h'|3i'# rand (10 * 20)
103 In the absence of parentheses,
104 the precedence of list operators such as print, sort or chmod is
105 either very high or very low depending on whether you look at the left
106 side of operator or the right side of it.
110 @ary = (1, 3, sort 4, 2);
111 print @ary; # prints 1324
114 the commas on the right of the sort are evaluated before the sort, but
115 the commas on the left are evaluated after.
116 In other words, list operators tend to gobble up all the arguments that
117 follow them, and then act like a simple term with regard to the preceding
119 Note that you have to be careful with parens:
123 # These evaluate exit before doing the print:
124 print($foo, exit); # Obviously not what you want.
125 print $foo, exit; # Nor is this.
128 # These do the print before evaluating exit:
129 (print $foo), exit; # This is what you want.
130 print($foo), exit; # Or this.
131 print ($foo), exit; # Or even this.
135 print ($foo & 255) + 1, "\en";
138 probably doesn't do what you expect at first glance.
140 A subroutine may be declared as follows:
147 Any arguments passed to the routine come in as array @_,
148 that is ($_[0], $_[1], .\|.\|.).
149 The array @_ is a local array, but its values are references to the
150 actual scalar parameters.
151 The return value of the subroutine is the value of the last expression
152 evaluated, and can be either an array value or a scalar value.
153 Alternately, a return statement may be used to specify the returned value and
155 To create local variables see the
159 A subroutine is called using the
161 operator or the & operator.
168 local($max) = pop(@_);
170 $max = $foo \|if \|$max < $foo;
176 $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
181 # get a line, combining continuation lines
182 # that start with whitespace
184 $thisline = $lookahead;
185 line: while ($lookahead = <STDIN>) {
186 if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
187 $thisline \|.= \|$lookahead;
196 $lookahead = <STDIN>; # get first line
197 while ($_ = do get_line(\|)) {
204 Use array assignment to a local list to name your formal arguments:
207 local($key, $value) = @_;
208 $foo{$key} = $value unless $foo{$key};
212 This also has the effect of turning call-by-reference into call-by-value,
213 since the assignment copies the values.
215 Subroutines may be called recursively.
216 If a subroutine is called using the & form, the argument list is optional.
217 If omitted, no @_ array is set up for the subroutine; the @_ array at the
218 time of the call is visible to subroutine instead.
221 do foo(1,2,3); # pass three arguments
222 &foo(1,2,3); # the same
224 do foo(); # pass a null list
226 &foo; # pass no arguments--more efficient
229 .Sh "Passing By Reference"
230 Sometimes you don't want to pass the value of an array to a subroutine but
231 rather the name of it, so that the subroutine can modify the global copy
232 of it rather than working with a local copy.
233 In perl you can refer to all the objects of a particular name by prefixing
234 the name with a star: *foo.
235 When evaluated, it produces a scalar value that represents all the objects
236 of that name, including any filehandle, format or subroutine.
237 When assigned to within a local() operation, it causes the name mentioned
238 to refer to whatever * value was assigned to it.
243 local(*someary) = @_;
244 foreach $elem (@someary) {
252 Assignment to *name is currently recommended only inside a local().
253 You can actually assign to *name anywhere, but the previous referent of
254 *name may be stranded forever.
255 This may or may not bother you.
257 Note that scalars are already passed by reference, so you can modify scalar
258 arguments without using this mechanism by referring explicitly to the $_[nnn]
260 You can modify all the elements of an array by passing all the elements
261 as scalars, but you have to use the * mechanism to push, pop or change the
263 The * mechanism will probably be more efficient in any case.
265 Since a *name value contains unprintable binary data, if it is used as
266 an argument in a print, or as a %s argument in a printf or sprintf, it
267 then has the value '*name', just so it prints out pretty.
269 Even if you don't want to modify an array, this mechanism is useful for
270 passing multiple arrays in a single LIST, since normally the LIST mechanism
271 will merge all the array values so that you can't extract out the
273 .Sh "Regular Expressions"
274 The patterns used in pattern matching are regular expressions such as
275 those supplied in the Version 8 regexp routines.
276 (In fact, the routines are derived from Henry Spencer's freely redistributable
277 reimplementation of the V8 routines.)
278 In addition, \ew matches an alphanumeric character (including \*(L"_\*(R") and \eW a nonalphanumeric.
279 Word boundaries may be matched by \eb, and non-boundaries by \eB.
280 A whitespace character is matched by \es, non-whitespace by \eS.
281 A numeric character is matched by \ed, non-numeric by \eD.
282 You may use \ew, \es and \ed within character classes.
283 Also, \en, \er, \ef, \et and \eNNN have their normal interpretations.
284 Within character classes \eb represents backspace rather than a word boundary.
285 Alternatives may be separated by |.
286 The bracketing construct \|(\ .\|.\|.\ \|) may also be used, in which case \e<digit>
287 matches the digit'th substring, where digit can range from 1 to 9.
288 (Outside of the pattern, always use $ instead of \e in front of the digit.
289 The scope of $<digit> (and $\`, $& and $\')
290 extends to the end of the enclosing BLOCK or eval string, or to
291 the next pattern match with subexpressions.
292 The \e<digit> notation sometimes works outside the current pattern, but should
294 $+ returns whatever the last bracket match matched.
295 $& returns the entire matched string.
296 ($0 used to return the same thing, but not any more.)
297 $\` returns everything before the matched string.
298 $\' returns everything after the matched string.
302 s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/; # swap first two words
305 if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
312 By default, the ^ character is only guaranteed to match at the beginning
314 the $ character only at the end (or before the newline at the end)
317 does certain optimizations with the assumption that the string contains
319 The behavior of ^ and $ on embedded newlines will be inconsistent.
320 You may, however, wish to treat a string as a multi-line buffer, such that
321 the ^ will match after any newline within the string, and $ will match
323 At the cost of a little more overhead, you can do this by setting the variable
325 Setting it back to 0 makes
327 revert to its old behavior.
329 To facilitate multi-line substitutions, the . character never matches a newline
331 In particular, the following leaves a newline on the $_ string:
335 s/.*(some_string).*/$1/;
337 If the newline is unwanted, try one of
339 s/.*(some_string).*\en/$1/;
340 s/.*(some_string)[^\e000]*/$1/;
341 s/.*(some_string)(.|\en)*/$1/;
342 chop; s/.*(some_string).*/$1/;
343 /(some_string)/ && ($_ = $1);
346 Any item of a regular expression may be followed with digits in curly brackets
347 of the form {n,m}, where n gives the minimum number of times to match the item
348 and m gives the maximum.
349 The form {n} is equivalent to {n,n} and matches exactly n times.
350 The form {n,} matches n or more times.
351 (If a curly bracket occurs in any other context, it is treated as a regular
353 The * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
355 There is no limit to the size of n or m, but large numbers will chew up
358 You will note that all backslashed metacharacters in
361 such as \eb, \ew, \en.
362 Unlike some other regular expression languages, there are no backslashed
363 symbols that aren't alphanumeric.
364 So anything that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} is always
365 interpreted as a literal character, not a metacharacter.
366 This makes it simple to quote a string that you want to use for a pattern
367 but that you are afraid might contain metacharacters.
368 Simply quote all the non-alphanumeric characters:
371 $pattern =~ s/(\eW)/\e\e$1/g;
375 Output record formats for use with the
377 operator may declared as follows:
386 If name is omitted, format \*(L"STDOUT\*(R" is defined.
387 FORMLIST consists of a sequence of lines, each of which may be of one of three
392 A \*(L"picture\*(R" line giving the format for one output line.
394 An argument line supplying values to plug into a picture line.
396 Picture lines are printed exactly as they look, except for certain fields
397 that substitute values into the line.
398 Each picture field starts with either @ or ^.
399 The @ field (not to be confused with the array marker @) is the normal
400 case; ^ fields are used
401 to do rudimentary multi-line text block filling.
402 The length of the field is supplied by padding out the field
403 with multiple <, >, or | characters to specify, respectively, left justification,
404 right justification, or centering.
405 As an alternate form of right justification,
406 you may also use # characters (with an optional .) to specify a numeric field.
407 If any of the values supplied for these fields contains a newline, only
408 the text up to the newline is printed.
409 The special field @* can be used for printing multi-line values.
410 It should appear by itself on a line.
412 The values are specified on the following line, in the same order as
414 The values should be separated by commas.
416 Picture fields that begin with ^ rather than @ are treated specially.
417 The value supplied must be a scalar variable name which contains a text
420 puts as much text as it can into the field, and then chops off the front
421 of the string so that the next time the variable is referenced,
422 more of the text can be printed.
423 Normally you would use a sequence of fields in a vertical stack to print
425 If you like, you can end the final field with .\|.\|., which will appear in the
426 output if the text was too long to appear in its entirety.
427 You can change which characters are legal to break on by changing the
428 variable $: to a list of the desired characters.
430 Since use of ^ fields can produce variable length records if the text to be
431 formatted is short, you can suppress blank lines by putting the tilde (~)
432 character anywhere in the line.
433 (Normally you should put it in the front if possible, for visibility.)
434 The tilde will be translated to a space upon output.
435 If you put a second tilde contiguous to the first, the line will be repeated
436 until all the fields on the line are exhausted.
437 (If you use a field of the @ variety, the expression you supply had better
438 not give the same value every time forever!)
447 # a report on the /etc/passwd file
450 Name Login Office Uid Gid Home
451 ------------------------------------------------------------------
454 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
455 $name, $login, $office,$uid,$gid, $home
459 # a report from a bug report form
462 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
464 ------------------------------------------------------------------
467 Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
469 Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
470 \& $index, $description
471 Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
472 \& $priority, $date, $description
473 From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
474 \& $from, $description
475 Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
476 \& $programmer, $description
477 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
479 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
481 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
483 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
485 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<...
493 It is possible to intermix prints with writes on the same output channel,
494 but you'll have to handle $\- (lines left on the page) yourself.
496 If you are printing lots of fields that are usually blank, you should consider
497 using the reset operator between records.
498 Not only is it more efficient, but it can prevent the bug of adding another
499 field and forgetting to zero it.
500 .Sh "Interprocess Communication"
501 The IPC facilities of perl are built on the Berkeley socket mechanism.
502 If you don't have sockets, you can ignore this section.
503 The calls have the same names as the corresponding system calls,
504 but the arguments tend to differ, for two reasons.
505 First, perl file handles work differently than C file descriptors.
506 Second, perl already knows the length of its strings, so you don't need
507 to pass that information.
508 Here is a sample client (untested):
511 ($them,$port) = @ARGV;
512 $port = 2345 unless $port;
513 $them = 'localhost' unless $them;
515 $SIG{'INT'} = 'dokill';
516 sub dokill { kill 9,$child if $child; }
518 require 'sys/socket.ph';
520 $sockaddr = 'S n a4 x8';
521 chop($hostname = `hostname`);
523 ($name, $aliases, $proto) = getprotobyname('tcp');
524 ($name, $aliases, $port) = getservbyname($port, 'tcp')
525 unless $port =~ /^\ed+$/;
527 ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
530 ($name, $aliases, $type, $len, $thisaddr) =
531 gethostbyname($hostname);
533 ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
535 $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
536 $that = pack($sockaddr, &AF_INET, $port, $thataddr);
538 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
539 bind(S, $this) || die "bind: $!";
540 connect(S, $that) || die "connect: $!";
542 select(S); $| = 1; select(stdout);
562 $port = 2345 unless $port;
564 require 'sys/socket.ph';
566 $sockaddr = 'S n a4 x8';
568 ($name, $aliases, $proto) = getprotobyname('tcp');
569 ($name, $aliases, $port) = getservbyname($port, 'tcp')
570 unless $port =~ /^\ed+$/;
572 $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
574 select(NS); $| = 1; select(stdout);
576 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
577 bind(S, $this) || die "bind: $!";
578 listen(S, 5) || die "connect: $!";
580 select(S); $| = 1; select(stdout);
583 print "Listening again\en";
584 ($addr = accept(NS,S)) || die $!;
585 print "accept ok\en";
587 ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
588 @inetaddr = unpack('C4',$inetaddr);
589 print "$af $port @inetaddr\en";
598 .Sh "Predefined Names"
599 The following names have special meaning to
601 I could have used alphabetic symbols for some of these, but I didn't want
602 to take the chance that someone would say reset \*(L"a\-zA\-Z\*(R" and wipe them all
604 You'll just have to suffer along with these silly symbols.
605 Most of them have reasonable mnemonics, or analogues in one of the shells.
607 The default input and pattern-searching space.
608 The following pairs are equivalent:
612 while (<>) {\|.\|.\|. # only equivalent in while!
613 while ($_ = <>) {\|.\|.\|.
617 $_ \|=~ \|/\|^Subject:/
628 (Mnemonic: underline is understood in certain operations.)
630 The current input line number of the last filehandle that was read.
632 Remember that only an explicit close on the filehandle resets the line number.
633 Since <> never does an explicit close, line numbers increase across ARGV files
634 (but see examples under eof).
635 (Mnemonic: many programs use . to mean the current line number.)
637 The input record separator, newline by default.
640 RS variable, including treating blank lines as delimiters
641 if set to the null string.
642 If set to a value longer than one character, only the first character is used.
643 (Mnemonic: / is used to delimit line boundaries when quoting poetry.)
645 The output field separator for the print operator.
646 Ordinarily the print operator simply prints out the comma separated fields
648 In order to get behavior more like
650 set this variable as you would set
652 OFS variable to specify what is printed between fields.
653 (Mnemonic: what is printed when there is a , in your print statement.)
655 This is like $, except that it applies to array values interpolated into
656 a double-quoted string (or similar interpreted string).
658 (Mnemonic: obvious, I think.)
660 The output record separator for the print operator.
661 Ordinarily the print operator simply prints out the comma separated fields
662 you specify, with no trailing newline or record separator assumed.
663 In order to get behavior more like
665 set this variable as you would set
667 ORS variable to specify what is printed at the end of the print.
668 (Mnemonic: you set $\e instead of adding \en at the end of the print.
669 Also, it's just like /, but it's what you get \*(L"back\*(R" from
672 The output format for printed numbers.
673 This variable is a half-hearted attempt to emulate
676 There are times, however, when
680 have differing notions of what
682 Also, the initial value is %.20g rather than %.6g, so you need to set $#
686 (Mnemonic: # is the number sign.)
688 The current page number of the currently selected output channel.
689 (Mnemonic: % is page number in nroff.)
691 The current page length (printable lines) of the currently selected output
694 (Mnemonic: = has horizontal lines.)
696 The number of lines left on the page of the currently selected output channel.
697 (Mnemonic: lines_on_page \- lines_printed.)
699 The name of the current report format for the currently selected output
701 (Mnemonic: brother to $^.)
703 The name of the current top-of-page format for the currently selected output
705 (Mnemonic: points to top of page.)
707 If set to nonzero, forces a flush after every write or print on the currently
708 selected output channel.
712 will typically be line buffered if output is to the
713 terminal and block buffered otherwise.
714 Setting this variable is useful primarily when you are outputting to a pipe,
715 such as when you are running a
717 script under rsh and want to see the
718 output as it's happening.
719 (Mnemonic: when you want your pipes to be piping hot.)
721 The process number of the
724 (Mnemonic: same as shells.)
726 The status returned by the last pipe close, backtick (\`\`) command or
729 Note that this is the status word returned by the wait() system
730 call, so the exit value of the subprocess is actually ($? >> 8).
731 $? & 255 gives which signal, if any, the process died from, and whether
732 there was a core dump.
733 (Mnemonic: similar to sh and ksh.)
735 The string matched by the last pattern match (not counting any matches hidden
736 within a BLOCK or eval enclosed by the current BLOCK).
737 (Mnemonic: like & in some editors.)
739 The string preceding whatever was matched by the last pattern match
740 (not counting any matches hidden within a BLOCK or eval enclosed by the current
742 (Mnemonic: \` often precedes a quoted string.)
744 The string following whatever was matched by the last pattern match
745 (not counting any matches hidden within a BLOCK or eval enclosed by the current
747 (Mnemonic: \' often follows a quoted string.)
754 print "$\`:$&:$\'\en"; # prints abc:def:ghi
758 The last bracket matched by the last search pattern.
759 This is useful if you don't know which of a set of alternative patterns
764 /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
767 (Mnemonic: be positive and forward looking.)
769 Set to 1 to do multiline matching within a string, 0 to tell
771 that it can assume that strings contain a single line, for the purpose
772 of optimizing pattern matches.
773 Pattern matches on strings containing multiple newlines can produce confusing
774 results when $* is 0.
776 (Mnemonic: * matches multiple things.)
778 Contains the name of the file containing the
780 script being executed.
781 (Mnemonic: same as sh and ksh.)
783 Contains the subpattern from the corresponding set of parentheses in the last
784 pattern matched, not counting patterns matched in nested blocks that have
786 (Mnemonic: like \edigit.)
788 The index of the first element in an array, and of the first character in
790 Default is 0, but you could set it to 1 to make
795 when subscripting and when evaluating the index() and substr() functions.
796 (Mnemonic: [ begins subscripts.)
798 The string printed out when you say \*(L"perl -v\*(R".
799 It can be used to determine at the beginning of a script whether the perl
800 interpreter executing the script is in the right range of versions.
801 If used in a numeric context, returns the version + patchlevel / 1000.
806 # see if getc is available
807 ($version,$patchlevel) =
808 $] =~ /(\ed+\e.\ed+).*\enPatch level: (\ed+)/;
809 print STDERR "(No filename completion available.)\en"
810 if $version * 1000 + $patchlevel < 2016;
812 or, used numerically,
814 warn "No checksumming!\en" if $] < 3.019;
817 (Mnemonic: Is this version of perl in the right bracket?)
819 The subscript separator for multi-dimensional array emulation.
820 If you refer to an associative array element as
826 $foo{join($;, $a, $b, $c)}
830 @foo{$a,$b,$c} # a slice--note the @
834 ($foo{$a},$foo{$b},$foo{$c})
837 Default is "\e034", the same as SUBSEP in
839 Note that if your keys contain binary data there might not be any safe
841 (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
842 Yeah, I know, it's pretty lame, but $, is already taken for something more
845 If used in a numeric context, yields the current value of errno, with all the
847 (This means that you shouldn't depend on the value of $! to be anything
848 in particular unless you've gotten a specific error return indicating a
850 If used in a string context, yields the corresponding system error string.
851 You can assign to $! in order to set errno
852 if, for instance, you want $! to return the string for error n, or you want
853 to set the exit value for the die operator.
854 (Mnemonic: What just went bang?)
856 The perl syntax error message from the last eval command.
857 If null, the last eval parsed and executed correctly (although the operations
858 you invoked may have failed in the normal fashion).
859 (Mnemonic: Where was the syntax error \*(L"at\*(R"?)
861 The real uid of this process.
862 (Mnemonic: it's the uid you came FROM, if you're running setuid.)
864 The effective uid of this process.
869 $< = $>; # set real uid to the effective uid
870 ($<,$>) = ($>,$<); # swap real and effective uid
873 (Mnemonic: it's the uid you went TO, if you're running setuid.)
874 Note: $< and $> can only be swapped on machines supporting setreuid().
876 The real gid of this process.
877 If you are on a machine that supports membership in multiple groups
878 simultaneously, gives a space separated list of groups you are in.
879 The first number is the one returned by getgid(), and the subsequent ones
880 by getgroups(), one of which may be the same as the first number.
881 (Mnemonic: parentheses are used to GROUP things.
882 The real gid is the group you LEFT, if you're running setgid.)
884 The effective gid of this process.
885 If you are on a machine that supports membership in multiple groups
886 simultaneously, gives a space separated list of groups you are in.
887 The first number is the one returned by getegid(), and the subsequent ones
888 by getgroups(), one of which may be the same as the first number.
889 (Mnemonic: parentheses are used to GROUP things.
890 The effective gid is the group that's RIGHT for you, if you're running setgid.)
892 Note: $<, $>, $( and $) can only be set on machines that support the
893 corresponding set[re][ug]id() routine.
894 $( and $) can only be swapped on machines supporting setregid().
896 The current set of characters after which a string may be broken to
897 fill continuation fields (starting with ^) in a format.
898 Default is "\ \en-", to break on whitespace or hyphens.
899 (Mnemonic: a \*(L"colon\*(R" in poetry is a part of a line.)
901 contains the name of the current file when reading from <>.
903 The array ARGV contains the command line arguments intended for the script.
904 Note that $#ARGV is the generally number of arguments minus one, since
905 $ARGV[0] is the first argument, NOT the command name.
906 See $0 for the command name.
908 The array INC contains the list of places to look for
911 evaluated by the \*(L"do EXPR\*(R" command or the \*(L"require\*(R" command.
912 It initially consists of the arguments to any
914 command line switches, followed
917 library, probably \*(L"/usr/local/lib/perl\*(R",
918 followed by \*(L".\*(R", to represent the current directory.
920 The associative array INC contains entries for each filename that has
921 been included via \*(L"do\*(R" or \*(L"require\*(R".
922 The key is the filename you specified, and the value is the location of
923 the file actually found.
924 The \*(L"require\*(R" command uses this array to determine whether
925 a given file has already been included.
927 The associative array ENV contains your current environment.
928 Setting a value in ENV changes the environment for child processes.
930 The associative array SIG is used to set signal handlers for various signals.
935 sub handler { # 1st argument is signal name
937 print "Caught a SIG$sig\-\|\-shutting down\en";
942 $SIG{\'INT\'} = \'handler\';
943 $SIG{\'QUIT\'} = \'handler\';
945 $SIG{\'INT\'} = \'DEFAULT\'; # restore default action
946 $SIG{\'QUIT\'} = \'IGNORE\'; # ignore SIGQUIT
949 The SIG array only contains values for the signals actually set within
952 Perl provides a mechanism for alternate namespaces to protect packages from
953 stomping on each others variables.
954 By default, a perl script starts compiling into the package known as \*(L"main\*(R".
957 declaration, you can switch namespaces.
958 The scope of the package declaration is from the declaration itself to the end
959 of the enclosing block (the same scope as the local() operator).
960 Typically it would be the first declaration in a file to be included by
961 the \*(L"require\*(R" operator.
962 You can switch into a package in more than one place; it merely influences
963 which symbol table is used by the compiler for the rest of that block.
964 You can refer to variables and filehandles in other packages by prefixing
965 the identifier with the package name and a single quote.
966 If the package name is null, the \*(L"main\*(R" package as assumed.
968 Only identifiers starting with letters are stored in the packages symbol
970 All other symbols are kept in package \*(L"main\*(R".
971 In addition, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC
972 and SIG are forced to be in package \*(L"main\*(R", even when used for
973 other purposes than their built-in one.
974 Note also that, if you have a package called \*(L"m\*(R", \*(L"s\*(R"
975 or \*(L"y\*(R", the you can't use the qualified form of an identifier since it
976 will be interpreted instead as a pattern match, a substitution
979 Eval'ed strings are compiled in the package in which the eval was compiled
981 (Assignments to $SIG{}, however, assume the signal handler specified is in the
983 Qualify the signal handler name if you wish to have a signal handler in
985 For an example, examine perldb.pl in the perl library.
986 It initially switches to the DB package so that the debugger doesn't interfere
987 with variables in the script you are trying to debug.
988 At various points, however, it temporarily switches back to the main package
989 to evaluate various expressions in the context of the main package.
991 The symbol table for a package happens to be stored in the associative array
992 of that name prepended with an underscore.
993 The value in each entry of the associative array is
994 what you are referring to when you use the *name notation.
995 In fact, the following have the same effect (in package main, anyway),
996 though the first is more
997 efficient because it does the symbol table lookups at compile time:
1002 local($_main{'foo'}) = $_main{'bar'};
1005 You can use this to print out all the variables in a package, for instance.
1006 Here is dumpvar.pl from the perl library:
1013 \& local(*stab) = eval("*_$package");
1014 \& while (($key,$val) = each(%stab)) {
1016 \& local(*entry) = $val;
1017 \& if (defined $entry) {
1018 \& print "\e$$key = '$entry'\en";
1021 \& if (defined @entry) {
1022 \& print "\e@$key = (\en";
1023 \& foreach $num ($[ .. $#entry) {
1024 \& print " $num\et'",$entry[$num],"'\en";
1029 \& if ($key ne "_$package" && defined %entry) {
1030 \& print "\e%$key = (\en";
1031 \& foreach $key (sort keys(%entry)) {
1032 \& print " $key\et'",$entry{$key},"'\en";
1041 Note that, even though the subroutine is compiled in package dumpvar, the
1042 name of the subroutine is qualified so that its name is inserted into package
1045 Each programmer will, of course, have his or her own preferences in regards
1046 to formatting, but there are some general guidelines that will make your
1047 programs easier to read.
1049 Just because you CAN do something a particular way doesn't mean that
1050 you SHOULD do it that way.
1052 is designed to give you several ways to do anything, so consider picking
1053 the most readable one.
1056 open(FOO,$foo) || die "Can't open $foo: $!";
1060 die "Can't open $foo: $!" unless open(FOO,$foo);
1062 because the second way hides the main point of the statement in a
1066 print "Starting analysis\en" if $verbose;
1070 $verbose && print "Starting analysis\en";
1072 since the main point isn't whether the user typed -v or not.
1074 Similarly, just because an operator lets you assume default arguments
1075 doesn't mean that you have to make use of the defaults.
1076 The defaults are there for lazy systems programmers writing one-shot
1078 If you want your program to be readable, consider supplying the argument.
1080 Along the same lines, just because you
1082 omit parentheses in many places doesn't mean that you ought to:
1085 return print reverse sort num values array;
1086 return print(reverse(sort num (values(%array))));
1089 When in doubt, parenthesize.
1090 At the very least it will let some poor schmuck bounce on the % key in vi.
1092 Don't go through silly contortions to exit a loop at the top or the
1095 provides the "last" operator so you can exit in the middle.
1096 Just outdent it a little to make it more visible:
1110 Don't be afraid to use loop labels\*(--they're there to enhance readability as
1111 well as to allow multi-level loop breaks.
1114 For portability, when using features that may not be implemented on every
1115 machine, test the construct in an eval to see if it fails.
1116 If you know what version or patchlevel a particular feature was implemented,
1117 you can test $] to see if it will be there.
1119 Choose mnemonic identifiers.
1127 switch, your script will be run under a debugging monitor.
1128 It will halt before the first executable statement and ask you for a
1131 Prints out a help message.
1136 Executes until it reaches the beginning of another statement.
1139 Executes over subroutine calls, until it reaches the beginning of the
1143 Executes statements until it has finished the current subroutine.
1146 Executes until the next breakpoint is reached.
1148 Continue to the specified line.
1149 Inserts a one-time-only breakpoint at the specified line.
1152 .Ip "l min+incr" 12 4
1153 List incr+1 lines starting at min.
1154 If min is omitted, starts where last listing left off.
1155 If incr is omitted, previous value of incr is used.
1156 .Ip "l min-max" 12 4
1157 List lines in the indicated range.
1159 List just the indicated line.
1163 List previous window.
1165 List window around line.
1166 .Ip "l subname" 12 4
1168 If it's a long subroutine it just lists the beginning.
1169 Use \*(L"l\*(R" to list more.
1170 .Ip "/pattern/" 12 4
1171 Regular expression search forward for pattern; the final / is optional.
1172 .Ip "?pattern?" 12 4
1173 Regular expression search backward for pattern; the final ? is optional.
1175 List lines that have breakpoints or actions.
1177 Lists the names of all subroutines.
1179 Toggle trace mode on or off.
1180 .Ip "b line condition" 12 4
1182 If line is omitted, sets a breakpoint on the
1183 line that is about to be executed.
1184 If a condition is specified, it is evaluated each time the statement is
1185 reached and a breakpoint is taken only if the condition is true.
1186 Breakpoints may only be set on lines that begin an executable statement.
1187 .Ip "b subname condition" 12 4
1188 Set breakpoint at first executable line of subroutine.
1191 If line is omitted, deletes the breakpoint on the
1192 line that is about to be executed.
1194 Delete all breakpoints.
1195 .Ip "a line command" 12 4
1196 Set an action for line.
1197 A multi-line command may be entered by backslashing the newlines.
1199 Delete all line actions.
1200 .Ip "< command" 12 4
1201 Set an action to happen before every debugger prompt.
1202 A multi-line command may be entered by backslashing the newlines.
1203 .Ip "> command" 12 4
1204 Set an action to happen after the prompt when you've just given a command
1205 to return to executing the script.
1206 A multi-line command may be entered by backslashing the newlines.
1207 .Ip "V package" 12 4
1208 List all variables in package.
1209 Default is main package.
1211 Redo a debugging command.
1212 If number is omitted, redoes the previous command.
1213 .Ip "! -number" 12 4
1214 Redo the command that was that many commands ago.
1215 .Ip "H -number" 12 4
1216 Display last n commands.
1217 Only commands longer than one character are listed.
1218 If number is omitted, lists them all.
1222 Execute command as a perl statement.
1223 A missing semicolon will be supplied.
1225 Same as \*(L"print DB'OUT expr\*(R".
1226 The DB'OUT filehandle is opened to /dev/tty, regardless of where STDOUT
1227 may be redirected to.
1229 If you want to modify the debugger, copy perldb.pl from the perl library
1230 to your current directory and modify it as necessary.
1231 (You'll also have to put -I. on your command line.)
1232 You can do some customization by setting up a .perldb file which contains
1233 initialization code.
1234 For instance, you could make aliases like these:
1237 $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
1238 $DB'alias{'stop'} = 's/^stop (at|in)/b/';
1240 's/^\e./p "\e$DB\e'sub(\e$DB\e'line):\et",\e$DB\e'line[\e$DB\e'line]/';
1243 .Sh "Setuid Scripts"
1245 is designed to make it easy to write secure setuid and setgid scripts.
1246 Unlike shells, which are based on multiple substitution passes on each line
1249 uses a more conventional evaluation scheme with fewer hidden \*(L"gotchas\*(R".
1250 Additionally, since the language has more built-in functionality, it
1251 has to rely less upon external (and possibly untrustworthy) programs to
1252 accomplish its purposes.
1254 In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
1255 insecure, but this kernel feature can be disabled.
1258 can emulate the setuid and setgid mechanism when it notices the otherwise
1259 useless setuid/gid bits on perl scripts.
1260 If the kernel feature isn't disabled,
1262 will complain loudly that your setuid script is insecure.
1263 You'll need to either disable the kernel setuid script feature, or put
1264 a C wrapper around the script.
1266 When perl is executing a setuid script, it takes special precautions to
1267 prevent you from falling into any obvious traps.
1268 (In some ways, a perl script is more secure than the corresponding
1270 Any command line argument, environment variable, or input is marked as
1271 \*(L"tainted\*(R", and may not be used, directly or indirectly, in any
1272 command that invokes a subshell, or in any command that modifies files,
1273 directories or processes.
1274 Any variable that is set within an expression that has previously referenced
1275 a tainted value also becomes tainted (even if it is logically impossible
1276 for the tainted value to influence the variable).
1281 $foo = shift; # $foo is tainted
1282 $bar = $foo,\'bar\'; # $bar is also tainted
1283 $xxx = <>; # Tainted
1284 $path = $ENV{\'PATH\'}; # Tainted, but see below
1285 $abc = \'abc\'; # Not tainted
1288 system "echo $foo"; # Insecure
1289 system "/bin/echo", $foo; # Secure (doesn't use sh)
1290 system "echo $bar"; # Insecure
1291 system "echo $abc"; # Insecure until PATH set
1294 $ENV{\'PATH\'} = \'/bin:/usr/bin\';
1295 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1297 $path = $ENV{\'PATH\'}; # Not tainted
1298 system "echo $abc"; # Is secure now!
1301 open(FOO,"$foo"); # OK
1302 open(FOO,">$foo"); # Not OK
1304 open(FOO,"echo $foo|"); # Not OK, but...
1305 open(FOO,"-|") || exec \'echo\', $foo; # OK
1307 $zzz = `echo $foo`; # Insecure, zzz tainted
1309 unlink $abc,$foo; # Insecure
1310 umask $foo; # Insecure
1313 exec "echo $foo"; # Insecure
1314 exec "echo", $foo; # Secure (doesn't use sh)
1315 exec "sh", \'-c\', $foo; # Considered secure, alas
1318 The taintedness is associated with each scalar value, so some elements
1319 of an array can be tainted, and others not.
1321 If you try to do something insecure, you will get a fatal error saying
1322 something like \*(L"Insecure dependency\*(R" or \*(L"Insecure PATH\*(R".
1323 Note that you can still write an insecure system call or exec,
1324 but only by explicitly doing something like the last example above.
1325 You can also bypass the tainting mechanism by referencing
1328 presumes that if you reference a substring using $1, $2, etc, you knew
1329 what you were doing when you wrote the pattern:
1332 $ARGV[0] =~ /^\-P(\ew+)$/;
1333 $printer = $1; # Not tainted
1336 This is fairly secure since \ew+ doesn't match shell metacharacters.
1337 Use of .+ would have been insecure, but
1339 doesn't check for that, so you must be careful with your patterns.
1340 This is the ONLY mechanism for untainting user supplied filenames if you
1341 want to do file operations on them (unless you make $> equal to $<).
1343 It's also possible to get into trouble with other operations that don't care
1344 whether they use tainted values.
1345 Make judicious use of the file tests in dealing with any user-supplied
1347 When possible, do opens and such after setting $> = $<.
1349 doesn't prevent you from opening tainted filenames for reading, so be
1350 careful what you print out.
1351 The tainting mechanism is intended to prevent stupid mistakes, not to remove
1352 the need for thought.
1355 uses PATH in executing subprocesses, and in finding the script if \-S
1357 HOME or LOGDIR are used if chdir has no argument.
1361 uses no environment variables, except to make them available
1362 to the script being executed, and to child processes.
1363 However, scripts running setuid would do well to execute the following lines
1364 before doing anything else, just to keep people honest:
1368 $ENV{\'PATH\'} = \'/bin:/usr/bin\'; # or whatever you need
1369 $ENV{\'SHELL\'} = \'/bin/sh\' if $ENV{\'SHELL\'} ne \'\';
1370 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1374 Larry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
1376 MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk>
1378 /tmp/perl\-eXXXXXX temporary file for
1382 a2p awk to perl translator
1384 s2p sed to perl translator
1386 Compilation errors will tell you the line number of the error, with an
1387 indication of the next token or token type that was to be examined.
1388 (In the case of a script passed to
1394 is counted as one line.)
1396 Setuid scripts have additional constraints that can produce error messages
1397 such as \*(L"Insecure dependency\*(R".
1398 See the section on setuid scripts.
1402 users should take special note of the following:
1404 Semicolons are required after all simple statements in
1407 is not a statement delimiter.
1409 Curly brackets are required on ifs and whiles.
1411 Variables begin with $ or @ in
1414 Arrays index from 0 unless you set $[.
1415 Likewise string positions in substr() and index().
1417 You have to decide whether your array has numeric or string indices.
1419 Associative array values do not spring into existence upon mere reference.
1421 You have to decide whether you want to use string or numeric comparisons.
1423 Reading an input line does not split it for you. You get to split it yourself
1427 operator has different arguments.
1429 The current input line is normally in $_, not $0.
1430 It generally does not have the newline stripped.
1431 ($0 is the name of the program executed.)
1433 $<digit> does not refer to fields\*(--it refers to substrings matched by the last
1438 statement does not add field and record separators unless you set
1441 You must open your files before you print to them.
1443 The range operator is \*(L".\|.\*(R", not comma.
1444 (The comma operator works as in C.)
1446 The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
1447 (\*(L"~\*(R" is the one's complement operator, as in C.)
1449 The exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
1450 (\*(L"^\*(R" is the XOR operator, as in C.)
1452 The concatenation operator is \*(L".\*(R", not the null string.
1453 (Using the null string would render \*(L"/pat/ /pat/\*(R" unparsable,
1454 since the third slash would be interpreted as a division operator\*(--the
1455 tokener is in fact slightly context sensitive for operators like /, ?, and <.
1456 And in fact, . itself can be the beginning of a number.)
1464 The following variables work differently
1468 ARGC \h'|2.5i'$#ARGV
1470 FILENAME\h'|2.5i'$ARGV
1471 FNR \h'|2.5i'$. \- something
1472 FS \h'|2.5i'(whatever you like)
1473 NF \h'|2.5i'$#Fld, or some such
1478 RLENGTH \h'|2.5i'length($&)
1480 RSTART \h'|2.5i'length($\`)
1485 When in doubt, run the
1487 construct through a2p and see what it gives you.
1489 Cerebral C programmers should take note of the following:
1491 Curly brackets are required on ifs and whiles.
1493 You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
1504 There's no switch statement.
1506 Variables begin with $ or @ in
1509 Printf does not implement *.
1511 Comments begin with #, not /*.
1513 You can't take the address of anything.
1515 ARGV must be capitalized.
1517 The \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
1519 Signal handlers deal with signal names, not numbers.
1523 programmers should take note of the following:
1525 Backreferences in substitutions use $ rather than \e.
1527 The pattern matching metacharacters (, ), and | do not have backslashes in front.
1529 The range operator is .\|. rather than comma.
1531 Sharp shell programmers should take note of the following:
1533 The backtick operator does variable interpretation without regard to the
1534 presence of single quotes in the command.
1536 The backtick operator does no translation of the return value, unlike csh.
1538 Shells (especially csh) do several levels of substitution on each command line.
1540 does substitution only in certain constructs such as double quotes,
1541 backticks, angle brackets and search patterns.
1543 Shells interpret scripts a little bit at a time.
1545 compiles the whole program before executing it.
1547 The arguments are available via @ARGV, not $1, $2, etc.
1549 The environment is not automatically made available as variables.
1553 is at the mercy of your machine's definitions of various operations
1554 such as type casting, atof() and sprintf().
1556 If your stdio requires an seek or eof between reads and writes on a particular
1560 While none of the built-in data types have any arbitrary size limits (apart
1561 from memory size), there are still a few arbitrary limits:
1562 a given identifier may not be longer than 255 characters;
1563 sprintf is limited on many machines to 128 characters per field (unless the format
1564 specifier is exactly %s);
1565 and no component of your PATH may be longer than 255 if you use \-S.
1568 actually stands for Pathologically Eclectic Rubbish Lister, but don't tell