1 ''' Beginning of part 4
2 ''' $Header: perl_man.4,v 3.0.1.10 90/08/09 04:47:35 lwall Locked $
4 ''' $Log: perl.man.4,v $
5 ''' Revision 3.0.1.10 90/08/09 04:47:35 lwall
6 ''' patch19: added require operator
7 ''' patch19: added numeric interpretation of $]
9 ''' Revision 3.0.1.9 90/08/03 11:15:58 lwall
10 ''' patch19: Intermediate diffs for Randal
12 ''' Revision 3.0.1.8 90/03/27 16:19:31 lwall
13 ''' patch16: MSDOS support
15 ''' Revision 3.0.1.7 90/03/14 12:29:50 lwall
16 ''' patch15: man page falsely states that you can't subscript array values
18 ''' Revision 3.0.1.6 90/03/12 16:54:04 lwall
19 ''' patch13: improved documentation of *name
21 ''' Revision 3.0.1.5 90/02/28 18:01:52 lwall
22 ''' patch9: $0 is now always the command name
24 ''' Revision 3.0.1.4 89/12/21 20:12:39 lwall
25 ''' patch7: documented that package'filehandle works as well as $package'variable
26 ''' patch7: documented which identifiers are always in package main
28 ''' Revision 3.0.1.3 89/11/17 15:32:25 lwall
29 ''' patch5: fixed some manual typos and indent problems
30 ''' patch5: clarified difference between $! and $@
32 ''' Revision 3.0.1.2 89/11/11 04:46:40 lwall
33 ''' patch2: made some line breaks depend on troff vs. nroff
34 ''' patch2: clarified operation of ^ and $ when $* is false
36 ''' Revision 3.0.1.1 89/10/26 23:18:43 lwall
37 ''' patch1: documented the desirability of unnecessary parentheses
39 ''' Revision 3.0 89/10/18 15:21:55 lwall
44 operators have the following associativity and precedence:
47 nonassoc\h'|1i'print printf exec system sort reverse
48 \h'1.5i'chmod chown kill unlink utime die return
50 right\h'|1i'= += \-= *= etc.
57 nonassoc\h'|1i'== != eq ne
58 nonassoc\h'|1i'< > <= >= lt gt le ge
59 nonassoc\h'|1i'chdir exit eval reset sleep rand umask
60 nonassoc\h'|1i'\-r \-w \-x etc.
65 right\h'|1i'! ~ and unary minus
67 nonassoc\h'|1i'++ \-\|\-
68 left\h'|1i'\*(L'(\*(R'
71 As mentioned earlier, if any list operator (print, etc.) or
72 any unary operator (chdir, etc.)
73 is followed by a left parenthesis as the next token on the same line,
74 the operator and arguments within parentheses are taken to
75 be of highest precedence, just like a normal function call.
79 chdir $foo || die;\h'|3i'# (chdir $foo) || die
80 chdir($foo) || die;\h'|3i'# (chdir $foo) || die
81 chdir ($foo) || die;\h'|3i'# (chdir $foo) || die
82 chdir +($foo) || die;\h'|3i'# (chdir $foo) || die
84 but, because * is higher precedence than ||:
86 chdir $foo * 20;\h'|3i'# chdir ($foo * 20)
87 chdir($foo) * 20;\h'|3i'# (chdir $foo) * 20
88 chdir ($foo) * 20;\h'|3i'# (chdir $foo) * 20
89 chdir +($foo) * 20;\h'|3i'# chdir ($foo * 20)
91 rand 10 * 20;\h'|3i'# rand (10 * 20)
92 rand(10) * 20;\h'|3i'# (rand 10) * 20
93 rand (10) * 20;\h'|3i'# (rand 10) * 20
94 rand +(10) * 20;\h'|3i'# rand (10 * 20)
97 In the absence of parentheses,
98 the precedence of list operators such as print, sort or chmod is
99 either very high or very low depending on whether you look at the left
100 side of operator or the right side of it.
104 @ary = (1, 3, sort 4, 2);
105 print @ary; # prints 1324
108 the commas on the right of the sort are evaluated before the sort, but
109 the commas on the left are evaluated after.
110 In other words, list operators tend to gobble up all the arguments that
111 follow them, and then act like a simple term with regard to the preceding
113 Note that you have to be careful with parens:
117 # These evaluate exit before doing the print:
118 print($foo, exit); # Obviously not what you want.
119 print $foo, exit; # Nor is this.
122 # These do the print before evaluating exit:
123 (print $foo), exit; # This is what you want.
124 print($foo), exit; # Or this.
125 print ($foo), exit; # Or even this.
129 print ($foo & 255) + 1, "\en";
132 probably doesn't do what you expect at first glance.
134 A subroutine may be declared as follows:
141 Any arguments passed to the routine come in as array @_,
142 that is ($_[0], $_[1], .\|.\|.).
143 The array @_ is a local array, but its values are references to the
144 actual scalar parameters.
145 The return value of the subroutine is the value of the last expression
146 evaluated, and can be either an array value or a scalar value.
147 Alternately, a return statement may be used to specify the returned value and
149 To create local variables see the
153 A subroutine is called using the
155 operator or the & operator.
162 local($max) = pop(@_);
164 $max = $foo \|if \|$max < $foo;
170 $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
175 # get a line, combining continuation lines
176 # that start with whitespace
178 $thisline = $lookahead;
179 line: while ($lookahead = <STDIN>) {
180 if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
181 $thisline \|.= \|$lookahead;
190 $lookahead = <STDIN>; # get first line
191 while ($_ = do get_line(\|)) {
198 Use array assignment to a local list to name your formal arguments:
201 local($key, $value) = @_;
202 $foo{$key} = $value unless $foo{$key};
206 This also has the effect of turning call-by-reference into call-by-value,
207 since the assignment copies the values.
209 Subroutines may be called recursively.
210 If a subroutine is called using the & form, the argument list is optional.
211 If omitted, no @_ array is set up for the subroutine; the @_ array at the
212 time of the call is visible to subroutine instead.
215 do foo(1,2,3); # pass three arguments
216 &foo(1,2,3); # the same
218 do foo(); # pass a null list
220 &foo; # pass no arguments--more efficient
223 .Sh "Passing By Reference"
224 Sometimes you don't want to pass the value of an array to a subroutine but
225 rather the name of it, so that the subroutine can modify the global copy
226 of it rather than working with a local copy.
227 In perl you can refer to all the objects of a particular name by prefixing
228 the name with a star: *foo.
229 When evaluated, it produces a scalar value that represents all the objects
230 of that name, including any filehandle, format or subroutine.
231 When assigned to within a local() operation, it causes the name mentioned
232 to refer to whatever * value was assigned to it.
237 local(*someary) = @_;
238 foreach $elem (@someary) {
246 Assignment to *name is currently recommended only inside a local().
247 You can actually assign to *name anywhere, but the previous referent of
248 *name may be stranded forever.
249 This may or may not bother you.
251 Note that scalars are already passed by reference, so you can modify scalar
252 arguments without using this mechanism by referring explicitly to the $_[nnn]
254 You can modify all the elements of an array by passing all the elements
255 as scalars, but you have to use the * mechanism to push, pop or change the
257 The * mechanism will probably be more efficient in any case.
259 Since a *name value contains unprintable binary data, if it is used as
260 an argument in a print, or as a %s argument in a printf or sprintf, it
261 then has the value '*name', just so it prints out pretty.
263 Even if you don't want to modify an array, this mechanism is useful for
264 passing multiple arrays in a single LIST, since normally the LIST mechanism
265 will merge all the array values so that you can't extract out the
267 .Sh "Regular Expressions"
268 The patterns used in pattern matching are regular expressions such as
269 those supplied in the Version 8 regexp routines.
270 (In fact, the routines are derived from Henry Spencer's freely redistributable
271 reimplementation of the V8 routines.)
272 In addition, \ew matches an alphanumeric character (including \*(L"_\*(R") and \eW a nonalphanumeric.
273 Word boundaries may be matched by \eb, and non-boundaries by \eB.
274 A whitespace character is matched by \es, non-whitespace by \eS.
275 A numeric character is matched by \ed, non-numeric by \eD.
276 You may use \ew, \es and \ed within character classes.
277 Also, \en, \er, \ef, \et and \eNNN have their normal interpretations.
278 Within character classes \eb represents backspace rather than a word boundary.
279 Alternatives may be separated by |.
280 The bracketing construct \|(\ .\|.\|.\ \|) may also be used, in which case \e<digit>
281 matches the digit'th substring, where digit can range from 1 to 9.
282 (Outside of the pattern, always use $ instead of \e in front of the digit.
283 The scope of $<digit> (and $\`, $& and $\')
284 extends to the end of the enclosing BLOCK or eval string, or to
285 the next pattern match with subexpressions.
286 The \e<digit> notation sometimes works outside the current pattern, but should
288 $+ returns whatever the last bracket match matched.
289 $& returns the entire matched string.
290 ($0 used to return the same thing, but not any more.)
291 $\` returns everything before the matched string.
292 $\' returns everything after the matched string.
296 s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/; # swap first two words
299 if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
306 By default, the ^ character is only guaranteed to match at the beginning
308 the $ character only at the end (or before the newline at the end)
311 does certain optimizations with the assumption that the string contains
313 The behavior of ^ and $ on embedded newlines will be inconsistent.
314 You may, however, wish to treat a string as a multi-line buffer, such that
315 the ^ will match after any newline within the string, and $ will match
317 At the cost of a little more overhead, you can do this by setting the variable
319 Setting it back to 0 makes
321 revert to its old behavior.
323 To facilitate multi-line substitutions, the . character never matches a newline
325 In particular, the following leaves a newline on the $_ string:
329 s/.*(some_string).*/$1/;
331 If the newline is unwanted, try one of
333 s/.*(some_string).*\en/$1/;
334 s/.*(some_string)[^\e000]*/$1/;
335 s/.*(some_string)(.|\en)*/$1/;
336 chop; s/.*(some_string).*/$1/;
337 /(some_string)/ && ($_ = $1);
340 Any item of a regular expression may be followed with digits in curly brackets
341 of the form {n,m}, where n gives the minimum number of times to match the item
342 and m gives the maximum.
343 The form {n} is equivalent to {n,n} and matches exactly n times.
344 The form {n,} matches n or more times.
345 (If a curly bracket occurs in any other context, it is treated as a regular
347 The * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
349 There is no limit to the size of n or m, but large numbers will chew up
352 You will note that all backslashed metacharacters in
355 such as \eb, \ew, \en.
356 Unlike some other regular expression languages, there are no backslashed
357 symbols that aren't alphanumeric.
358 So anything that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} is always
359 interpreted as a literal character, not a metacharacter.
360 This makes it simple to quote a string that you want to use for a pattern
361 but that you are afraid might contain metacharacters.
362 Simply quote all the non-alphanumeric characters:
365 $pattern =~ s/(\eW)/\e\e$1/g;
369 Output record formats for use with the
371 operator may declared as follows:
380 If name is omitted, format \*(L"STDOUT\*(R" is defined.
381 FORMLIST consists of a sequence of lines, each of which may be of one of three
386 A \*(L"picture\*(R" line giving the format for one output line.
388 An argument line supplying values to plug into a picture line.
390 Picture lines are printed exactly as they look, except for certain fields
391 that substitute values into the line.
392 Each picture field starts with either @ or ^.
393 The @ field (not to be confused with the array marker @) is the normal
394 case; ^ fields are used
395 to do rudimentary multi-line text block filling.
396 The length of the field is supplied by padding out the field
397 with multiple <, >, or | characters to specify, respectively, left justification,
398 right justification, or centering.
399 If any of the values supplied for these fields contains a newline, only
400 the text up to the newline is printed.
401 The special field @* can be used for printing multi-line values.
402 It should appear by itself on a line.
404 The values are specified on the following line, in the same order as
406 The values should be separated by commas.
408 Picture fields that begin with ^ rather than @ are treated specially.
409 The value supplied must be a scalar variable name which contains a text
412 puts as much text as it can into the field, and then chops off the front
413 of the string so that the next time the variable is referenced,
414 more of the text can be printed.
415 Normally you would use a sequence of fields in a vertical stack to print
417 If you like, you can end the final field with .\|.\|., which will appear in the
418 output if the text was too long to appear in its entirety.
419 You can change which characters are legal to break on by changing the
420 variable $: to a list of the desired characters.
422 Since use of ^ fields can produce variable length records if the text to be
423 formatted is short, you can suppress blank lines by putting the tilde (~)
424 character anywhere in the line.
425 (Normally you should put it in the front if possible, for visibility.)
426 The tilde will be translated to a space upon output.
427 If you put a second tilde contiguous to the first, the line will be repeated
428 until all the fields on the line are exhausted.
429 (If you use a field of the @ variety, the expression you supply had better
430 not give the same value every time forever!)
439 # a report on the /etc/passwd file
442 Name Login Office Uid Gid Home
443 ------------------------------------------------------------------
446 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
447 $name, $login, $office,$uid,$gid, $home
451 # a report from a bug report form
454 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
456 ------------------------------------------------------------------
459 Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
461 Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
462 \& $index, $description
463 Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
464 \& $priority, $date, $description
465 From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
466 \& $from, $description
467 Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
468 \& $programmer, $description
469 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
471 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
473 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
475 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
477 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<...
485 It is possible to intermix prints with writes on the same output channel,
486 but you'll have to handle $\- (lines left on the page) yourself.
488 If you are printing lots of fields that are usually blank, you should consider
489 using the reset operator between records.
490 Not only is it more efficient, but it can prevent the bug of adding another
491 field and forgetting to zero it.
492 .Sh "Interprocess Communication"
493 The IPC facilities of perl are built on the Berkeley socket mechanism.
494 If you don't have sockets, you can ignore this section.
495 The calls have the same names as the corresponding system calls,
496 but the arguments tend to differ, for two reasons.
497 First, perl file handles work differently than C file descriptors.
498 Second, perl already knows the length of its strings, so you don't need
499 to pass that information.
500 Here is a sample client (untested):
503 ($them,$port) = @ARGV;
504 $port = 2345 unless $port;
505 $them = 'localhost' unless $them;
507 $SIG{'INT'} = 'dokill';
508 sub dokill { kill 9,$child if $child; }
510 require 'sys/socket.ph';
512 $sockaddr = 'S n a4 x8';
513 chop($hostname = `hostname`);
515 ($name, $aliases, $proto) = getprotobyname('tcp');
516 ($name, $aliases, $port) = getservbyname($port, 'tcp')
517 unless $port =~ /^\ed+$/;
519 ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
522 ($name, $aliases, $type, $len, $thisaddr) =
523 gethostbyname($hostname);
525 ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
527 $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
528 $that = pack($sockaddr, &AF_INET, $port, $thataddr);
530 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
531 bind(S, $this) || die "bind: $!";
532 connect(S, $that) || die "connect: $!";
534 select(S); $| = 1; select(stdout);
554 $port = 2345 unless $port;
556 require 'sys/socket.ph';
558 $sockaddr = 'S n a4 x8';
560 ($name, $aliases, $proto) = getprotobyname('tcp');
561 ($name, $aliases, $port) = getservbyname($port, 'tcp')
562 unless $port =~ /^\ed+$/;
564 $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
566 select(NS); $| = 1; select(stdout);
568 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
569 bind(S, $this) || die "bind: $!";
570 listen(S, 5) || die "connect: $!";
572 select(S); $| = 1; select(stdout);
575 print "Listening again\en";
576 ($addr = accept(NS,S)) || die $!;
577 print "accept ok\en";
579 ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
580 @inetaddr = unpack('C4',$inetaddr);
581 print "$af $port @inetaddr\en";
590 .Sh "Predefined Names"
591 The following names have special meaning to
593 I could have used alphabetic symbols for some of these, but I didn't want
594 to take the chance that someone would say reset \*(L"a\-zA\-Z\*(R" and wipe them all
596 You'll just have to suffer along with these silly symbols.
597 Most of them have reasonable mnemonics, or analogues in one of the shells.
599 The default input and pattern-searching space.
600 The following pairs are equivalent:
604 while (<>) {\|.\|.\|. # only equivalent in while!
605 while ($_ = <>) {\|.\|.\|.
609 $_ \|=~ \|/\|^Subject:/
620 (Mnemonic: underline is understood in certain operations.)
622 The current input line number of the last filehandle that was read.
624 Remember that only an explicit close on the filehandle resets the line number.
625 Since <> never does an explicit close, line numbers increase across ARGV files
626 (but see examples under eof).
627 (Mnemonic: many programs use . to mean the current line number.)
629 The input record separator, newline by default.
632 RS variable, including treating blank lines as delimiters
633 if set to the null string.
634 If set to a value longer than one character, only the first character is used.
635 (Mnemonic: / is used to delimit line boundaries when quoting poetry.)
637 The output field separator for the print operator.
638 Ordinarily the print operator simply prints out the comma separated fields
640 In order to get behavior more like
642 set this variable as you would set
644 OFS variable to specify what is printed between fields.
645 (Mnemonic: what is printed when there is a , in your print statement.)
647 This is like $, except that it applies to array values interpolated into
648 a double-quoted string (or similar interpreted string).
650 (Mnemonic: obvious, I think.)
652 The output record separator for the print operator.
653 Ordinarily the print operator simply prints out the comma separated fields
654 you specify, with no trailing newline or record separator assumed.
655 In order to get behavior more like
657 set this variable as you would set
659 ORS variable to specify what is printed at the end of the print.
660 (Mnemonic: you set $\e instead of adding \en at the end of the print.
661 Also, it's just like /, but it's what you get \*(L"back\*(R" from
664 The output format for printed numbers.
665 This variable is a half-hearted attempt to emulate
668 There are times, however, when
672 have differing notions of what
674 Also, the initial value is %.20g rather than %.6g, so you need to set $#
678 (Mnemonic: # is the number sign.)
680 The current page number of the currently selected output channel.
681 (Mnemonic: % is page number in nroff.)
683 The current page length (printable lines) of the currently selected output
686 (Mnemonic: = has horizontal lines.)
688 The number of lines left on the page of the currently selected output channel.
689 (Mnemonic: lines_on_page \- lines_printed.)
691 The name of the current report format for the currently selected output
693 (Mnemonic: brother to $^.)
695 The name of the current top-of-page format for the currently selected output
697 (Mnemonic: points to top of page.)
699 If set to nonzero, forces a flush after every write or print on the currently
700 selected output channel.
704 will typically be line buffered if output is to the
705 terminal and block buffered otherwise.
706 Setting this variable is useful primarily when you are outputting to a pipe,
707 such as when you are running a
709 script under rsh and want to see the
710 output as it's happening.
711 (Mnemonic: when you want your pipes to be piping hot.)
713 The process number of the
716 (Mnemonic: same as shells.)
718 The status returned by the last pipe close, backtick (\`\`) command or
721 Note that this is the status word returned by the wait() system
722 call, so the exit value of the subprocess is actually ($? >> 8).
723 $? & 255 gives which signal, if any, the process died from, and whether
724 there was a core dump.
725 (Mnemonic: similar to sh and ksh.)
727 The string matched by the last pattern match (not counting any matches hidden
728 within a BLOCK or eval enclosed by the current BLOCK).
729 (Mnemonic: like & in some editors.)
731 The string preceding whatever was matched by the last pattern match
732 (not counting any matches hidden within a BLOCK or eval enclosed by the current
734 (Mnemonic: \` often precedes a quoted string.)
736 The string following 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 follows a quoted string.)
746 print "$\`:$&:$\'\en"; # prints abc:def:ghi
750 The last bracket matched by the last search pattern.
751 This is useful if you don't know which of a set of alternative patterns
756 /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
759 (Mnemonic: be positive and forward looking.)
761 Set to 1 to do multiline matching within a string, 0 to tell
763 that it can assume that strings contain a single line, for the purpose
764 of optimizing pattern matches.
765 Pattern matches on strings containing multiple newlines can produce confusing
766 results when $* is 0.
768 (Mnemonic: * matches multiple things.)
770 Contains the name of the file containing the
772 script being executed.
773 (Mnemonic: same as sh and ksh.)
775 Contains the subpattern from the corresponding set of parentheses in the last
776 pattern matched, not counting patterns matched in nested blocks that have
778 (Mnemonic: like \edigit.)
780 The index of the first element in an array, and of the first character in
782 Default is 0, but you could set it to 1 to make
787 when subscripting and when evaluating the index() and substr() functions.
788 (Mnemonic: [ begins subscripts.)
790 The string printed out when you say \*(L"perl -v\*(R".
791 It can be used to determine at the beginning of a script whether the perl
792 interpreter executing the script is in the right range of versions.
793 If used in a numeric context, returns the version + patchlevel / 1000.
798 # see if getc is available
799 ($version,$patchlevel) =
800 $] =~ /(\ed+\e.\ed+).*\enPatch level: (\ed+)/;
801 print STDERR "(No filename completion available.)\en"
802 if $version * 1000 + $patchlevel < 2016;
804 or, used numerically,
806 warn "No checksumming!\n" if $] < 3.019;
809 (Mnemonic: Is this version of perl in the right bracket?)
811 The subscript separator for multi-dimensional array emulation.
812 If you refer to an associative array element as
818 $foo{join($;, $a, $b, $c)}
822 @foo{$a,$b,$c} # a slice--note the @
826 ($foo{$a},$foo{$b},$foo{$c})
829 Default is "\e034", the same as SUBSEP in
831 Note that if your keys contain binary data there might not be any safe
833 (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
834 Yeah, I know, it's pretty lame, but $, is already taken for something more
837 If used in a numeric context, yields the current value of errno, with all the
839 (This means that you shouldn't depend on the value of $! to be anything
840 in particular unless you've gotten a specific error return indicating a
842 If used in a string context, yields the corresponding system error string.
843 You can assign to $! in order to set errno
844 if, for instance, you want $! to return the string for error n, or you want
845 to set the exit value for the die operator.
846 (Mnemonic: What just went bang?)
848 The perl syntax error message from the last eval command.
849 If null, the last eval parsed and executed correctly (although the operations
850 you invoked may have failed in the normal fashion).
851 (Mnemonic: Where was the syntax error \*(L"at\*(R"?)
853 The real uid of this process.
854 (Mnemonic: it's the uid you came FROM, if you're running setuid.)
856 The effective uid of this process.
861 $< = $>; # set real uid to the effective uid
862 ($<,$>) = ($>,$<); # swap real and effective uid
865 (Mnemonic: it's the uid you went TO, if you're running setuid.)
866 Note: $< and $> can only be swapped on machines supporting setreuid().
868 The real gid of this process.
869 If you are on a machine that supports membership in multiple groups
870 simultaneously, gives a space separated list of groups you are in.
871 The first number is the one returned by getgid(), and the subsequent ones
872 by getgroups(), one of which may be the same as the first number.
873 (Mnemonic: parentheses are used to GROUP things.
874 The real gid is the group you LEFT, if you're running setgid.)
876 The effective 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 getegid(), 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 effective gid is the group that's RIGHT for you, if you're running setgid.)
884 Note: $<, $>, $( and $) can only be set on machines that support the
885 corresponding set[re][ug]id() routine.
886 $( and $) can only be swapped on machines supporting setregid().
888 The current set of characters after which a string may be broken to
889 fill continuation fields (starting with ^) in a format.
890 Default is "\ \en-", to break on whitespace or hyphens.
891 (Mnemonic: a \*(L"colon\*(R" in poetry is a part of a line.)
893 contains the name of the current file when reading from <>.
895 The array ARGV contains the command line arguments intended for the script.
896 Note that $#ARGV is the generally number of arguments minus one, since
897 $ARGV[0] is the first argument, NOT the command name.
898 See $0 for the command name.
900 The array INC contains the list of places to look for
903 evaluated by the \*(L"do EXPR\*(R" command or the \*(L"require\*(r" command.
904 It initially consists of the arguments to any
906 command line switches, followed
909 library, probably \*(L"/usr/local/lib/perl\*(R",
910 followed by \*(L".\*(R", to represent the current directory.
912 The associative array INC contains entries for each filename that has
913 been included via \*(L"do\*(R" or \*(L"require\*(R".
914 The key is the filename you specified, and the value is the location of
915 the file actually found.
916 The \*(L"require\*(R" command uses this array to determine whether
917 a given file has already been included.
919 The associative array ENV contains your current environment.
920 Setting a value in ENV changes the environment for child processes.
922 The associative array SIG is used to set signal handlers for various signals.
927 sub handler { # 1st argument is signal name
929 print "Caught a SIG$sig\-\|\-shutting down\en";
934 $SIG{\'INT\'} = \'handler\';
935 $SIG{\'QUIT\'} = \'handler\';
937 $SIG{\'INT\'} = \'DEFAULT\'; # restore default action
938 $SIG{\'QUIT\'} = \'IGNORE\'; # ignore SIGQUIT
941 The SIG array only contains values for the signals actually set within
944 Perl provides a mechanism for alternate namespaces to protect packages from
945 stomping on each others variables.
946 By default, a perl script starts compiling into the package known as \*(L"main\*(R".
949 declaration, you can switch namespaces.
950 The scope of the package declaration is from the declaration itself to the end
951 of the enclosing block (the same scope as the local() operator).
952 Typically it would be the first declaration in a file to be included by
953 the \*(L"require\*(R" operator.
954 You can switch into a package in more than one place; it merely influences
955 which symbol table is used by the compiler for the rest of that block.
956 You can refer to variables and filehandles in other packages by prefixing
957 the identifier with the package name and a single quote.
958 If the package name is null, the \*(L"main\*(R" package as assumed.
960 Only identifiers starting with letters are stored in the packages symbol
962 All other symbols are kept in package \*(L"main\*(R".
963 In addition, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC
964 and SIG are forced to be in package \*(L"main\*(R", even when used for
965 other purposes than their built-in one.
966 Note also that, if you have a package called \*(L"m\*(R", \*(L"s\*(R"
967 or \*(L"y\*(R", the you can't use the qualified form of an identifier since it
968 will be interpreted instead as a pattern match, a substitution
971 Eval'ed strings are compiled in the package in which the eval was compiled
973 (Assignments to $SIG{}, however, assume the signal handler specified is in the
975 Qualify the signal handler name if you wish to have a signal handler in
977 For an example, examine perldb.pl in the perl library.
978 It initially switches to the DB package so that the debugger doesn't interfere
979 with variables in the script you are trying to debug.
980 At various points, however, it temporarily switches back to the main package
981 to evaluate various expressions in the context of the main package.
983 The symbol table for a package happens to be stored in the associative array
984 of that name prepended with an underscore.
985 The value in each entry of the associative array is
986 what you are referring to when you use the *name notation.
987 In fact, the following have the same effect (in package main, anyway),
988 though the first is more
989 efficient because it does the symbol table lookups at compile time:
994 local($_main{'foo'}) = $_main{'bar'};
997 You can use this to print out all the variables in a package, for instance.
998 Here is dumpvar.pl from the perl library:
1005 \& local(*stab) = eval("*_$package");
1006 \& while (($key,$val) = each(%stab)) {
1008 \& local(*entry) = $val;
1009 \& if (defined $entry) {
1010 \& print "\e$$key = '$entry'\en";
1013 \& if (defined @entry) {
1014 \& print "\e@$key = (\en";
1015 \& foreach $num ($[ .. $#entry) {
1016 \& print " $num\et'",$entry[$num],"'\en";
1021 \& if ($key ne "_$package" && defined %entry) {
1022 \& print "\e%$key = (\en";
1023 \& foreach $key (sort keys(%entry)) {
1024 \& print " $key\et'",$entry{$key},"'\en";
1033 Note that, even though the subroutine is compiled in package dumpvar, the
1034 name of the subroutine is qualified so that its name is inserted into package
1037 Each programmer will, of course, have his or her own preferences in regards
1038 to formatting, but there are some general guidelines that will make your
1039 programs easier to read.
1041 Just because you CAN do something a particular way doesn't mean that
1042 you SHOULD do it that way.
1044 is designed to give you several ways to do anything, so consider picking
1045 the most readable one.
1048 open(FOO,$foo) || die "Can't open $foo: $!";
1052 die "Can't open $foo: $!" unless open(FOO,$foo);
1054 because the second way hides the main point of the statement in a
1058 print "Starting analysis\en" if $verbose;
1062 $verbose && print "Starting analysis\en";
1064 since the main point isn't whether the user typed -v or not.
1066 Similarly, just because an operator lets you assume default arguments
1067 doesn't mean that you have to make use of the defaults.
1068 The defaults are there for lazy systems programmers writing one-shot
1070 If you want your program to be readable, consider supplying the argument.
1072 Along the same lines, just because you
1074 omit parentheses in many places doesn't mean that you ought to:
1077 return print reverse sort num values array;
1078 return print(reverse(sort num (values(%array))));
1081 When in doubt, parenthesize.
1082 At the very least it will let some poor schmuck bounce on the % key in vi.
1084 Don't go through silly contortions to exit a loop at the top or the
1087 provides the "last" operator so you can exit in the middle.
1088 Just outdent it a little to make it more visible:
1102 Don't be afraid to use loop labels\*(--they're there to enhance readability as
1103 well as to allow multi-level loop breaks.
1106 For portability, when using features that may not be implemented on every
1107 machine, test the construct in an eval to see if it fails.
1108 If you know what version or patchlevel a particular feature was implemented,
1109 you can test $] to see if it will be there.
1111 Choose mnemonic identifiers.
1119 switch, your script will be run under a debugging monitor.
1120 It will halt before the first executable statement and ask you for a
1123 Prints out a help message.
1128 Executes until it reaches the beginning of another statement.
1131 Executes over subroutine calls, until it reaches the beginning of the
1135 Executes statements until it has finished the current subroutine.
1138 Executes until the next breakpoint is reached.
1140 Continue to the specified line.
1141 Inserts a one-time-only breakpoint at the specified line.
1144 .Ip "l min+incr" 12 4
1145 List incr+1 lines starting at min.
1146 If min is omitted, starts where last listing left off.
1147 If incr is omitted, previous value of incr is used.
1148 .Ip "l min-max" 12 4
1149 List lines in the indicated range.
1151 List just the indicated line.
1155 List previous window.
1157 List window around line.
1158 .Ip "l subname" 12 4
1160 If it's a long subroutine it just lists the beginning.
1161 Use \*(L"l\*(R" to list more.
1162 .Ip "/pattern/" 12 4
1163 Regular expression search forward for pattern; the final / is optional.
1164 .Ip "?pattern?" 12 4
1165 Regular expression search backward for pattern; the final ? is optional.
1167 List lines that have breakpoints or actions.
1169 Lists the names of all subroutines.
1171 Toggle trace mode on or off.
1172 .Ip "b line condition" 12 4
1174 If line is omitted, sets a breakpoint on the
1175 line that is about to be executed.
1176 If a condition is specified, it is evaluated each time the statement is
1177 reached and a breakpoint is taken only if the condition is true.
1178 Breakpoints may only be set on lines that begin an executable statement.
1179 .Ip "b subname condition" 12 4
1180 Set breakpoint at first executable line of subroutine.
1183 If line is omitted, deletes the breakpoint on the
1184 line that is about to be executed.
1186 Delete all breakpoints.
1187 .Ip "a line command" 12 4
1188 Set an action for line.
1189 A multi-line command may be entered by backslashing the newlines.
1191 Delete all line actions.
1192 .Ip "< command" 12 4
1193 Set an action to happen before every debugger prompt.
1194 A multi-line command may be entered by backslashing the newlines.
1195 .Ip "> command" 12 4
1196 Set an action to happen after the prompt when you've just given a command
1197 to return to executing the script.
1198 A multi-line command may be entered by backslashing the newlines.
1199 .Ip "V package" 12 4
1200 List all variables in package.
1201 Default is main package.
1203 Redo a debugging command.
1204 If number is omitted, redoes the previous command.
1205 .Ip "! -number" 12 4
1206 Redo the command that was that many commands ago.
1207 .Ip "H -number" 12 4
1208 Display last n commands.
1209 Only commands longer than one character are listed.
1210 If number is omitted, lists them all.
1214 Execute command as a perl statement.
1215 A missing semicolon will be supplied.
1217 Same as \*(L"print DB'OUT expr\*(R".
1218 The DB'OUT filehandle is opened to /dev/tty, regardless of where STDOUT
1219 may be redirected to.
1221 If you want to modify the debugger, copy perldb.pl from the perl library
1222 to your current directory and modify it as necessary.
1223 You can do some customization by setting up a .perldb file which contains
1224 initialization code.
1225 For instance, you could make aliases like these:
1228 $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
1229 $DB'alias{'stop'} = 's/^stop (at|in)/b/';
1231 's/^\e./p "\e$DB\e'sub(\e$DB\e'line):\et",\e$DB\e'line[\e$DB\e'line]/';
1234 .Sh "Setuid Scripts"
1236 is designed to make it easy to write secure setuid and setgid scripts.
1237 Unlike shells, which are based on multiple substitution passes on each line
1240 uses a more conventional evaluation scheme with fewer hidden \*(L"gotchas\*(R".
1241 Additionally, since the language has more built-in functionality, it
1242 has to rely less upon external (and possibly untrustworthy) programs to
1243 accomplish its purposes.
1245 In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
1246 insecure, but this kernel feature can be disabled.
1249 can emulate the setuid and setgid mechanism when it notices the otherwise
1250 useless setuid/gid bits on perl scripts.
1251 If the kernel feature isn't disabled,
1253 will complain loudly that your setuid script is insecure.
1254 You'll need to either disable the kernel setuid script feature, or put
1255 a C wrapper around the script.
1257 When perl is executing a setuid script, it takes special precautions to
1258 prevent you from falling into any obvious traps.
1259 (In some ways, a perl script is more secure than the corresponding
1261 Any command line argument, environment variable, or input is marked as
1262 \*(L"tainted\*(R", and may not be used, directly or indirectly, in any
1263 command that invokes a subshell, or in any command that modifies files,
1264 directories or processes.
1265 Any variable that is set within an expression that has previously referenced
1266 a tainted value also becomes tainted (even if it is logically impossible
1267 for the tainted value to influence the variable).
1272 $foo = shift; # $foo is tainted
1273 $bar = $foo,\'bar\'; # $bar is also tainted
1274 $xxx = <>; # Tainted
1275 $path = $ENV{\'PATH\'}; # Tainted, but see below
1276 $abc = \'abc\'; # Not tainted
1279 system "echo $foo"; # Insecure
1280 system "/bin/echo", $foo; # Secure (doesn't use sh)
1281 system "echo $bar"; # Insecure
1282 system "echo $abc"; # Insecure until PATH set
1285 $ENV{\'PATH\'} = \'/bin:/usr/bin\';
1286 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1288 $path = $ENV{\'PATH\'}; # Not tainted
1289 system "echo $abc"; # Is secure now!
1292 open(FOO,"$foo"); # OK
1293 open(FOO,">$foo"); # Not OK
1295 open(FOO,"echo $foo|"); # Not OK, but...
1296 open(FOO,"-|") || exec \'echo\', $foo; # OK
1298 $zzz = `echo $foo`; # Insecure, zzz tainted
1300 unlink $abc,$foo; # Insecure
1301 umask $foo; # Insecure
1304 exec "echo $foo"; # Insecure
1305 exec "echo", $foo; # Secure (doesn't use sh)
1306 exec "sh", \'-c\', $foo; # Considered secure, alas
1309 The taintedness is associated with each scalar value, so some elements
1310 of an array can be tainted, and others not.
1312 If you try to do something insecure, you will get a fatal error saying
1313 something like \*(L"Insecure dependency\*(R" or \*(L"Insecure PATH\*(R".
1314 Note that you can still write an insecure system call or exec,
1315 but only by explicitly doing something like the last example above.
1316 You can also bypass the tainting mechanism by referencing
1319 presumes that if you reference a substring using $1, $2, etc, you knew
1320 what you were doing when you wrote the pattern:
1323 $ARGV[0] =~ /^\-P(\ew+)$/;
1324 $printer = $1; # Not tainted
1327 This is fairly secure since \ew+ doesn't match shell metacharacters.
1328 Use of .+ would have been insecure, but
1330 doesn't check for that, so you must be careful with your patterns.
1331 This is the ONLY mechanism for untainting user supplied filenames if you
1332 want to do file operations on them (unless you make $> equal to $<).
1334 It's also possible to get into trouble with other operations that don't care
1335 whether they use tainted values.
1336 Make judicious use of the file tests in dealing with any user-supplied
1338 When possible, do opens and such after setting $> = $<.
1340 doesn't prevent you from opening tainted filenames for reading, so be
1341 careful what you print out.
1342 The tainting mechanism is intended to prevent stupid mistakes, not to remove
1343 the need for thought.
1346 uses PATH in executing subprocesses, and in finding the script if \-S
1348 HOME or LOGDIR are used if chdir has no argument.
1352 uses no environment variables, except to make them available
1353 to the script being executed, and to child processes.
1354 However, scripts running setuid would do well to execute the following lines
1355 before doing anything else, just to keep people honest:
1359 $ENV{\'PATH\'} = \'/bin:/usr/bin\'; # or whatever you need
1360 $ENV{\'SHELL\'} = \'/bin/sh\' if $ENV{\'SHELL\'} ne \'\';
1361 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1365 Larry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
1367 MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk>
1369 /tmp/perl\-eXXXXXX temporary file for
1373 a2p awk to perl translator
1375 s2p sed to perl translator
1377 Compilation errors will tell you the line number of the error, with an
1378 indication of the next token or token type that was to be examined.
1379 (In the case of a script passed to
1385 is counted as one line.)
1387 Setuid scripts have additional constraints that can produce error messages
1388 such as \*(L"Insecure dependency\*(R".
1389 See the section on setuid scripts.
1393 users should take special note of the following:
1395 Semicolons are required after all simple statements in
1398 is not a statement delimiter.
1400 Curly brackets are required on ifs and whiles.
1402 Variables begin with $ or @ in
1405 Arrays index from 0 unless you set $[.
1406 Likewise string positions in substr() and index().
1408 You have to decide whether your array has numeric or string indices.
1410 Associative array values do not spring into existence upon mere reference.
1412 You have to decide whether you want to use string or numeric comparisons.
1414 Reading an input line does not split it for you. You get to split it yourself
1418 operator has different arguments.
1420 The current input line is normally in $_, not $0.
1421 It generally does not have the newline stripped.
1422 ($0 is the name of the program executed.)
1424 $<digit> does not refer to fields\*(--it refers to substrings matched by the last
1429 statement does not add field and record separators unless you set
1432 You must open your files before you print to them.
1434 The range operator is \*(L".\|.\*(R", not comma.
1435 (The comma operator works as in C.)
1437 The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
1438 (\*(L"~\*(R" is the one's complement operator, as in C.)
1440 The exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
1441 (\*(L"^\*(R" is the XOR operator, as in C.)
1443 The concatenation operator is \*(L".\*(R", not the null string.
1444 (Using the null string would render \*(L"/pat/ /pat/\*(R" unparsable,
1445 since the third slash would be interpreted as a division operator\*(--the
1446 tokener is in fact slightly context sensitive for operators like /, ?, and <.
1447 And in fact, . itself can be the beginning of a number.)
1455 The following variables work differently
1459 ARGC \h'|2.5i'$#ARGV
1461 FILENAME\h'|2.5i'$ARGV
1462 FNR \h'|2.5i'$. \- something
1463 FS \h'|2.5i'(whatever you like)
1464 NF \h'|2.5i'$#Fld, or some such
1469 RLENGTH \h'|2.5i'length($&)
1471 RSTART \h'|2.5i'length($\`)
1476 When in doubt, run the
1478 construct through a2p and see what it gives you.
1480 Cerebral C programmers should take note of the following:
1482 Curly brackets are required on ifs and whiles.
1484 You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
1495 There's no switch statement.
1497 Variables begin with $ or @ in
1500 Printf does not implement *.
1502 Comments begin with #, not /*.
1504 You can't take the address of anything.
1506 ARGV must be capitalized.
1508 The \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
1510 Signal handlers deal with signal names, not numbers.
1514 programmers should take note of the following:
1516 Backreferences in substitutions use $ rather than \e.
1518 The pattern matching metacharacters (, ), and | do not have backslashes in front.
1520 The range operator is .\|. rather than comma.
1522 Sharp shell programmers should take note of the following:
1524 The backtick operator does variable interpretation without regard to the
1525 presence of single quotes in the command.
1527 The backtick operator does no translation of the return value, unlike csh.
1529 Shells (especially csh) do several levels of substitution on each command line.
1531 does substitution only in certain constructs such as double quotes,
1532 backticks, angle brackets and search patterns.
1534 Shells interpret scripts a little bit at a time.
1536 compiles the whole program before executing it.
1538 The arguments are available via @ARGV, not $1, $2, etc.
1540 The environment is not automatically made available as variables.
1544 is at the mercy of your machine's definitions of various operations
1545 such as type casting, atof() and sprintf().
1547 If your stdio requires an seek or eof between reads and writes on a particular
1551 While none of the built-in data types have any arbitrary size limits (apart
1552 from memory size), there are still a few arbitrary limits:
1553 a given identifier may not be longer than 255 characters;
1554 sprintf is limited on many machines to 128 characters per field (unless the format
1555 specifier is exactly %s);
1556 and no component of your PATH may be longer than 255 if you use \-S.
1559 actually stands for Pathologically Eclectic Rubbish Lister, but don't tell