1 ''' Beginning of part 4
2 ''' $Header: perl.man.4,v 3.0 89/10/18 15:21:55 lwall Locked $
4 ''' $Log: perl.man.4,v $
5 ''' Revision 3.0 89/10/18 15:21:55 lwall
10 operators have the following associativity and precedence:
13 nonassoc\h'|1i'print printf exec system sort reverse
14 \h'1.5i'chmod chown kill unlink utime die return
16 right\h'|1i'= += \-= *= etc.
23 nonassoc\h'|1i'== != eq ne
24 nonassoc\h'|1i'< > <= >= lt gt le ge
25 nonassoc\h'|1i'chdir exit eval reset sleep rand umask
26 nonassoc\h'|1i'\-r \-w \-x etc.
31 right\h'|1i'! ~ and unary minus
33 nonassoc\h'|1i'++ \-\|\-
34 left\h'|1i'\*(L'(\*(R'
37 As mentioned earlier, if any list operator (print, etc.) or
38 any unary operator (chdir, etc.)
39 is followed by a left parenthesis as the next token on the same line,
40 the operator and arguments within parentheses are taken to
41 be of highest precedence, just like a normal function call.
45 chdir $foo || die; # (chdir $foo) || die
46 chdir($foo) || die; # (chdir $foo) || die
47 chdir ($foo) || die; # (chdir $foo) || die
48 chdir +($foo) || die; # (chdir $foo) || die
50 but, because * is higher precedence than ||:
52 chdir $foo * 20; # chdir ($foo * 20)
53 chdir($foo) * 20; # (chdir $foo) * 20
54 chdir ($foo) * 20; # (chdir $foo) * 20
55 chdir +($foo) * 20; # chdir ($foo * 20)
57 rand 10 * 20; # rand (10 * 20)
58 rand(10) * 20; # (rand 10) * 20
59 rand (10) * 20; # (rand 10) * 20
60 rand +(10) * 20; # rand (10 * 20)
63 In the absence of parentheses,
64 the precedence of list operators such as print, sort or chmod is
65 either very high or very low depending on whether you look at the left
66 side of operator or the right side of it.
70 @ary = (1, 3, sort 4, 2);
71 print @ary; # prints 1324
74 the commas on the right of the sort are evaluated before the sort, but
75 the commas on the left are evaluated after.
76 In other words, list operators tend to gobble up all the arguments that
77 follow them, and then act like a simple term with regard to the preceding
79 Note that you have to be careful with parens:
83 # These evaluate exit before doing the print:
84 print($foo, exit); # Obviously not what you want.
85 print $foo, exit; # Nor is this.
88 # These do the print before evaluating exit:
89 (print $foo), exit; # This is what you want.
90 print($foo), exit; # Or this.
91 print ($foo), exit; # Or even this.
95 print ($foo & 255) + 1, "\en";
98 probably doesn't do what you expect at first glance.
100 A subroutine may be declared as follows:
107 Any arguments passed to the routine come in as array @_,
108 that is ($_[0], $_[1], .\|.\|.).
109 The array @_ is a local array, but its values are references to the
110 actual scalar parameters.
111 The return value of the subroutine is the value of the last expression
112 evaluated, and can be either an array value or a scalar value.
113 Alternately, a return statement may be used to specify the returned value and
115 To create local variables see the
119 A subroutine is called using the
121 operator or the & operator.
128 local($max) = pop(@_);
130 $max = $foo \|if \|$max < $foo;
136 $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
141 # get a line, combining continuation lines
142 # that start with whitespace
144 $thisline = $lookahead;
145 line: while ($lookahead = <STDIN>) {
146 if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
147 $thisline \|.= \|$lookahead;
156 $lookahead = <STDIN>; # get first line
157 while ($_ = do get_line(\|)) {
164 Use array assignment to a local list to name your formal arguments:
167 local($key, $value) = @_;
168 $foo{$key} = $value unless $foo{$key};
172 This also has the effect of turning call-by-reference into call-by-value,
173 since the assignment copies the values.
175 Subroutines may be called recursively.
176 If a subroutine is called using the & form, the argument list is optional.
177 If omitted, no @_ array is set up for the subroutine; the @_ array at the
178 time of the call is visible to subroutine instead.
181 do foo(1,2,3); # pass three arguments
182 &foo(1,2,3); # the same
184 do foo(); # pass a null list
186 &foo; # pass no arguments--more efficient
189 .Sh "Passing By Reference"
190 Sometimes you don't want to pass the value of an array to a subroutine but
191 rather the name of it, so that the subroutine can modify the global copy
192 of it rather than working with a local copy.
193 In perl you can refer to all the objects of a particular name by prefixing
194 the name with a star: *foo.
195 When evaluated, it produces a scalar value that represents all the objects
197 When assigned to within a local() operation, it causes the name mentioned
198 to refer to whatever * value was assigned to it.
203 local(*someary) = @_;
204 foreach $elem (@someary) {
212 Assignment to *name is currently recommended only inside a local().
213 You can actually assign to *name anywhere, but the previous referent of
214 *name may be stranded forever.
215 This may or may not bother you.
217 Note that scalars are already passed by reference, so you can modify scalar
218 arguments without using this mechanism by refering explicitly to the $_[nnn]
220 You can modify all the elements of an array by passing all the elements
221 as scalars, but you have to use the * mechanism to push, pop or change the
223 The * mechanism will probably be more efficient in any case.
225 Since a *name value contains unprintable binary data, if it is used as
226 an argument in a print, or as a %s argument in a printf or sprintf, it
227 then has the value '*name', just so it prints out pretty.
228 .Sh "Regular Expressions"
229 The patterns used in pattern matching are regular expressions such as
230 those supplied in the Version 8 regexp routines.
231 (In fact, the routines are derived from Henry Spencer's freely redistributable
232 reimplementation of the V8 routines.)
233 In addition, \ew matches an alphanumeric character (including \*(L"_\*(R") and \eW a nonalphanumeric.
234 Word boundaries may be matched by \eb, and non-boundaries by \eB.
235 A whitespace character is matched by \es, non-whitespace by \eS.
236 A numeric character is matched by \ed, non-numeric by \eD.
237 You may use \ew, \es and \ed within character classes.
238 Also, \en, \er, \ef, \et and \eNNN have their normal interpretations.
239 Within character classes \eb represents backspace rather than a word boundary.
240 Alternatives may be separated by |.
241 The bracketing construct \|(\ .\|.\|.\ \|) may also be used, in which case \e<digit>
242 matches the digit'th substring, where digit can range from 1 to 9.
243 (Outside of the pattern, always use $ instead of \e in front of the digit.
244 The scope of $<digit> (and $\`, $& and $\')
245 extends to the end of the enclosing BLOCK or eval string, or to
246 the next pattern match with subexpressions.
247 The \e<digit> notation sometimes works outside the current pattern, but should
249 $+ returns whatever the last bracket match matched.
250 $& returns the entire matched string.
251 ($0 normally returns the same thing, but don't depend on it.)
252 $\` returns everything before the matched string.
253 $\' returns everything after the matched string.
257 s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/; # swap first two words
260 if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
267 By default, the ^ character matches only the beginning of the string,
268 the $ character matches only at the end (or before the newline at the end)
271 does certain optimizations with the assumption that the string contains
273 You may, however, wish to treat a string as a multi-line buffer, such that
274 the ^ will match after any newline within the string, and $ will match
276 At the cost of a little more overhead, you can do this by setting the variable
278 Setting it back to 0 makes
280 revert to its old behavior.
282 To facilitate multi-line substitutions, the . character never matches a newline
284 In particular, the following leaves a newline on the $_ string:
288 s/.*(some_string).*/$1/;
290 If the newline is unwanted, try one of
292 s/.*(some_string).*\en/$1/;
293 s/.*(some_string)[^\e000]*/$1/;
294 s/.*(some_string)(.|\en)*/$1/;
295 chop; s/.*(some_string).*/$1/;
296 /(some_string)/ && ($_ = $1);
299 Any item of a regular expression may be followed with digits in curly brackets
300 of the form {n,m}, where n gives the minimum number of times to match the item
301 and m gives the maximum.
302 The form {n} is equivalent to {n,n} and matches exactly n times.
303 The form {n,} matches n or more times.
304 (If a curly bracket occurs in any other context, it is treated as a regular
306 The * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
308 There is no limit to the size of n or m, but large numbers will chew up
311 You will note that all backslashed metacharacters in
314 such as \eb, \ew, \en.
315 Unlike some other regular expression languages, there are no backslashed
316 symbols that aren't alphanumeric.
317 So anything that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} is always
318 interpreted as a literal character, not a metacharacter.
319 This makes it simple to quote a string that you want to use for a pattern
320 but that you are afraid might contain metacharacters.
321 Simply quote all the non-alphanumeric characters:
324 $pattern =~ s/(\eW)/\e\e$1/g;
328 Output record formats for use with the
330 operator may declared as follows:
339 If name is omitted, format \*(L"STDOUT\*(R" is defined.
340 FORMLIST consists of a sequence of lines, each of which may be of one of three
345 A \*(L"picture\*(R" line giving the format for one output line.
347 An argument line supplying values to plug into a picture line.
349 Picture lines are printed exactly as they look, except for certain fields
350 that substitute values into the line.
351 Each picture field starts with either @ or ^.
352 The @ field (not to be confused with the array marker @) is the normal
353 case; ^ fields are used
354 to do rudimentary multi-line text block filling.
355 The length of the field is supplied by padding out the field
356 with multiple <, >, or | characters to specify, respectively, left justification,
357 right justification, or centering.
358 If any of the values supplied for these fields contains a newline, only
359 the text up to the newline is printed.
360 The special field @* can be used for printing multi-line values.
361 It should appear by itself on a line.
363 The values are specified on the following line, in the same order as
365 The values should be separated by commas.
367 Picture fields that begin with ^ rather than @ are treated specially.
368 The value supplied must be a scalar variable name which contains a text
371 puts as much text as it can into the field, and then chops off the front
372 of the string so that the next time the variable is referenced,
373 more of the text can be printed.
374 Normally you would use a sequence of fields in a vertical stack to print
376 If you like, you can end the final field with .\|.\|., which will appear in the
377 output if the text was too long to appear in its entirety.
378 You can change which characters are legal to break on by changing the
379 variable $: to a list of the desired characters.
381 Since use of ^ fields can produce variable length records if the text to be
382 formatted is short, you can suppress blank lines by putting the tilde (~)
383 character anywhere in the line.
384 (Normally you should put it in the front if possible, for visibility.)
385 The tilde will be translated to a space upon output.
386 If you put a second tilde contiguous to the first, the line will be repeated
387 until all the fields on the line are exhausted.
388 (If you use a field of the @ variety, the expression you supply had better
389 not give the same value every time forever!)
398 # a report on the /etc/passwd file
401 Name Login Office Uid Gid Home
402 ------------------------------------------------------------------
405 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
406 $name, $login, $office,$uid,$gid, $home
410 # a report from a bug report form
413 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
415 ------------------------------------------------------------------
418 Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
420 Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
421 \& $index, $description
422 Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
423 \& $priority, $date, $description
424 From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
425 \& $from, $description
426 Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
427 \& $programmer, $description
428 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
430 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
432 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
434 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
436 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<...
444 It is possible to intermix prints with writes on the same output channel,
445 but you'll have to handle $\- (lines left on the page) yourself.
447 If you are printing lots of fields that are usually blank, you should consider
448 using the reset operator between records.
449 Not only is it more efficient, but it can prevent the bug of adding another
450 field and forgetting to zero it.
451 .Sh "Interprocess Communication"
452 The IPC facilities of perl are built on the Berkeley socket mechanism.
453 If you don't have sockets, you can ignore this section.
454 The calls have the same names as the corresponding system calls,
455 but the arguments tend to differ, for two reasons.
456 First, perl file handles work differently than C file descriptors.
457 Second, perl already knows the length of its strings, so you don't need
458 to pass that information.
459 Here is a sample client (untested):
462 ($them,$port) = @ARGV;
463 $port = 2345 unless $port;
464 $them = 'localhost' unless $them;
466 $SIG{'INT'} = 'dokill';
467 sub dokill { kill 9,$child if $child; }
469 do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
471 $sockaddr = 'S n a4 x8';
472 chop($hostname = `hostname`);
474 ($name, $aliases, $proto) = getprotobyname('tcp');
475 ($name, $aliases, $port) = getservbyname($port, 'tcp')
476 unless $port =~ /^\ed+$/;;
477 ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
478 ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
480 $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
481 $that = pack($sockaddr, &AF_INET, $port, $thataddr);
483 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
484 bind(S, $this) || die "bind: $!";
485 connect(S, $that) || die "connect: $!";
487 select(S); $| = 1; select(stdout);
507 $port = 2345 unless $port;
509 do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
511 $sockaddr = 'S n a4 x8';
513 ($name, $aliases, $proto) = getprotobyname('tcp');
514 ($name, $aliases, $port) = getservbyname($port, 'tcp')
515 unless $port =~ /^\ed+$/;;
517 $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
519 select(NS); $| = 1; select(stdout);
521 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
522 bind(S, $this) || die "bind: $!";
523 listen(S, 5) || die "connect: $!";
525 select(S); $| = 1; select(stdout);
528 print "Listening again\en";
529 ($addr = accept(NS,S)) || die $!;
530 print "accept ok\en";
532 ($af,$port,$inetaddr) = unpack($pat,$addr);
533 @inetaddr = unpack('C4',$inetaddr);
534 print "$af $port @inetaddr\en";
543 .Sh "Predefined Names"
544 The following names have special meaning to
546 I could have used alphabetic symbols for some of these, but I didn't want
547 to take the chance that someone would say reset \*(L"a\-zA\-Z\*(R" and wipe them all
549 You'll just have to suffer along with these silly symbols.
550 Most of them have reasonable mnemonics, or analogues in one of the shells.
552 The default input and pattern-searching space.
553 The following pairs are equivalent:
557 while (<>) {\|.\|.\|. # only equivalent in while!
558 while ($_ = <>) {\|.\|.\|.
562 $_ \|=~ \|/\|^Subject:/
573 (Mnemonic: underline is understood in certain operations.)
575 The current input line number of the last filehandle that was read.
577 Remember that only an explicit close on the filehandle resets the line number.
578 Since <> never does an explicit close, line numbers increase across ARGV files
579 (but see examples under eof).
580 (Mnemonic: many programs use . to mean the current line number.)
582 The input record separator, newline by default.
585 RS variable, including treating blank lines as delimiters
586 if set to the null string.
587 If set to a value longer than one character, only the first character is used.
588 (Mnemonic: / is used to delimit line boundaries when quoting poetry.)
590 The output field separator for the print operator.
591 Ordinarily the print operator simply prints out the comma separated fields
593 In order to get behavior more like
595 set this variable as you would set
597 OFS variable to specify what is printed between fields.
598 (Mnemonic: what is printed when there is a , in your print statement.)
600 This is like $, except that it applies to array values interpolated into
601 a double-quoted string (or similar interpreted string).
603 (Mnemonic: obvious, I think.)
605 The output record separator for the print operator.
606 Ordinarily the print operator simply prints out the comma separated fields
607 you specify, with no trailing newline or record separator assumed.
608 In order to get behavior more like
610 set this variable as you would set
612 ORS variable to specify what is printed at the end of the print.
613 (Mnemonic: you set $\e instead of adding \en at the end of the print.
614 Also, it's just like /, but it's what you get \*(L"back\*(R" from
617 The output format for printed numbers.
618 This variable is a half-hearted attempt to emulate
621 There are times, however, when
625 have differing notions of what
627 Also, the initial value is %.20g rather than %.6g, so you need to set $#
631 (Mnemonic: # is the number sign.)
633 The current page number of the currently selected output channel.
634 (Mnemonic: % is page number in nroff.)
636 The current page length (printable lines) of the currently selected output
639 (Mnemonic: = has horizontal lines.)
641 The number of lines left on the page of the currently selected output channel.
642 (Mnemonic: lines_on_page \- lines_printed.)
644 The name of the current report format for the currently selected output
646 (Mnemonic: brother to $^.)
648 The name of the current top-of-page format for the currently selected output
650 (Mnemonic: points to top of page.)
652 If set to nonzero, forces a flush after every write or print on the currently
653 selected output channel.
657 will typically be line buffered if output is to the
658 terminal and block buffered otherwise.
659 Setting this variable is useful primarily when you are outputting to a pipe,
660 such as when you are running a
662 script under rsh and want to see the
663 output as it's happening.
664 (Mnemonic: when you want your pipes to be piping hot.)
666 The process number of the
669 (Mnemonic: same as shells.)
671 The status returned by the last pipe close, backtick (\`\`) command or
674 Note that this is the status word returned by the wait() system
675 call, so the exit value of the subprocess is actually ($? >> 8).
676 $? & 255 gives which signal, if any, the process died from, and whether
677 there was a core dump.
678 (Mnemonic: similar to sh and ksh.)
680 The string matched by the last pattern match (not counting any matches hidden
681 within a BLOCK or eval enclosed by the current BLOCK).
682 (Mnemonic: like & in some editors.)
684 The string preceding whatever was matched by the last pattern match
685 (not counting any matches hidden within a BLOCK or eval enclosed by the current
687 (Mnemonic: \` often precedes a quoted string.)
689 The string following whatever was matched by the last pattern match
690 (not counting any matches hidden within a BLOCK or eval enclosed by the current
692 (Mnemonic: \' often follows a quoted string.)
699 print "$\`:$&:$\'\en"; # prints abc:def:ghi
703 The last bracket matched by the last search pattern.
704 This is useful if you don't know which of a set of alternative patterns
709 /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
712 (Mnemonic: be positive and forward looking.)
714 Set to 1 to do multiline matching within a string, 0 to tell
716 that it can assume that strings contain a single line, for the purpose
717 of optimizing pattern matches.
718 Pattern matches on strings containing multiple newlines can produce confusing
719 results when $* is 0.
721 (Mnemonic: * matches multiple things.)
723 Contains the name of the file containing the
725 script being executed.
726 The value should be copied elsewhere before any pattern matching happens, which
728 (Mnemonic: same as sh and ksh.)
730 Contains the subpattern from the corresponding set of parentheses in the last
731 pattern matched, not counting patterns matched in nested blocks that have
733 (Mnemonic: like \edigit.)
735 The index of the first element in an array, and of the first character in
737 Default is 0, but you could set it to 1 to make
742 when subscripting and when evaluating the index() and substr() functions.
743 (Mnemonic: [ begins subscripts.)
745 The string printed out when you say \*(L"perl -v\*(R".
746 It can be used to determine at the beginning of a script whether the perl
747 interpreter executing the script is in the right range of versions.
752 # see if getc is available
753 ($version,$patchlevel) =
754 $] =~ /(\ed+\e.\ed+).*\enPatch level: (\ed+)/;
755 print STDERR "(No filename completion available.)\en"
756 if $version * 1000 + $patchlevel < 2016;
759 (Mnemonic: Is this version of perl in the right bracket?)
761 The subscript separator for multi-dimensional array emulation.
762 If you refer to an associative array element as
768 $foo{join($;, $a, $b, $c)}
772 @foo{$a,$b,$c} # a slice--note the @
776 ($foo{$a},$foo{$b},$foo{$c})
779 Default is "\e034", the same as SUBSEP in
781 Note that if your keys contain binary data there might not be any safe
783 (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
784 Yeah, I know, it's pretty lame, but $, is already taken for something more
787 If used in a numeric context, yields the current value of errno, with all the
789 If used in a string context, yields the corresponding system error string.
790 You can assign to $! in order to set errno
791 if, for instance, you want $! to return the string for error n, or you want
792 to set the exit value for the die operator.
793 (Mnemonic: What just went bang?)
795 The error message from the last eval command.
796 If null, the last eval parsed and executed correctly.
797 (Mnemonic: Where was the syntax error \*(L"at\*(R"?)
799 The real uid of this process.
800 (Mnemonic: it's the uid you came FROM, if you're running setuid.)
802 The effective uid of this process.
807 $< = $>; # set real uid to the effective uid
808 ($<,$>) = ($>,$<); # swap real and effective uid
811 (Mnemonic: it's the uid you went TO, if you're running setuid.)
812 Note: $< and $> can only be swapped on machines supporting setreuid().
814 The real gid of this process.
815 If you are on a machine that supports membership in multiple groups
816 simultaneously, gives a space separated list of groups you are in.
817 The first number is the one returned by getgid(), and the subsequent ones
818 by getgroups(), one of which may be the same as the first number.
819 (Mnemonic: parentheses are used to GROUP things.
820 The real gid is the group you LEFT, if you're running setgid.)
822 The effective gid of this process.
823 If you are on a machine that supports membership in multiple groups
824 simultaneously, gives a space separated list of groups you are in.
825 The first number is the one returned by getegid(), and the subsequent ones
826 by getgroups(), one of which may be the same as the first number.
827 (Mnemonic: parentheses are used to GROUP things.
828 The effective gid is the group that's RIGHT for you, if you're running setgid.)
830 Note: $<, $>, $( and $) can only be set on machines that support the
831 corresponding set[re][ug]id() routine.
832 $( and $) can only be swapped on machines supporting setregid().
834 The current set of characters after which a string may be broken to
835 fill continuation fields (starting with ^) in a format.
836 Default is "\ \en-", to break on whitespace or hyphens.
837 (Mnemonic: a \*(L"colon\*(R" in poetry is a part of a line.)
839 The array ARGV contains the command line arguments intended for the script.
840 Note that $#ARGV is the generally number of arguments minus one, since
841 $ARGV[0] is the first argument, NOT the command name.
842 See $0 for the command name.
844 The array INC contains the list of places to look for
847 evaluated by the \*(L"do EXPR\*(R" command.
848 It initially consists of the arguments to any
850 command line switches, followed
853 library, probably \*(L"/usr/local/lib/perl\*(R".
855 The associative array ENV contains your current environment.
856 Setting a value in ENV changes the environment for child processes.
858 The associative array SIG is used to set signal handlers for various signals.
863 sub handler { # 1st argument is signal name
865 print "Caught a SIG$sig\-\|\-shutting down\en";
870 $SIG{\'INT\'} = \'handler\';
871 $SIG{\'QUIT\'} = \'handler\';
873 $SIG{\'INT\'} = \'DEFAULT\'; # restore default action
874 $SIG{\'QUIT\'} = \'IGNORE\'; # ignore SIGQUIT
877 The SIG array only contains values for the signals actually set within
880 Perl provides a mechanism for alternate namespaces to protect packages from
881 stomping on each others variables.
882 By default, a perl script starts compiling into the package known as \*(L"main\*(R".
885 declaration, you can switch namespaces.
886 The scope of the package declaration is from the declaration itself to the end
887 of the enclosing block (the same scope as the local() operator).
888 Typically it would be the first declaration in a file to be included by
889 the \*(L"do FILE\*(R" operator.
890 You can switch into a package in more than one place; it merely influences
891 which symbol table is used by the compiler for the rest of that block.
892 You can refer to variables in other packages by prefixing the name with
893 the package name and a single quote.
894 If the package name is null, the \*(L"main\*(R" package as assumed.
895 Eval'ed strings are compiled in the package in which the eval was compiled
897 (Assignments to $SIG{}, however, assume the signal handler specified is in the
899 Qualify the signal handler name if you wish to have a signal handler in
901 For an example, examine perldb.pl in the perl library.
902 It initially switches to the DB package so that the debugger doesn't interfere
903 with variables in the script you are trying to debug.
904 At various points, however, it temporarily switches back to the main package
905 to evaluate various expressions in the context of the main package.
907 The symbol table for a package happens to be stored in the associative array
908 of that name prepended with an underscore.
909 The value in each entry of the associative array is
910 what you are referring to when you use the *name notation.
911 In fact, the following have the same effect (in package main, anyway),
912 though the first is more
913 efficient because it does the symbol table lookups at compile time:
918 local($_main{'foo'}) = $_main{'bar'};
921 You can use this to print out all the variables in a package, for instance.
922 Here is dumpvar.pl from the perl library:
929 \& local(*stab) = eval("*_$package");
930 \& while (($key,$val) = each(%stab)) {
932 \& local(*entry) = $val;
933 \& if (defined $entry) {
934 \& print "\e$$key = '$entry'\en";
937 \& if (defined @entry) {
938 \& print "\e@$key = (\en";
939 \& foreach $num ($[ .. $#entry) {
940 \& print " $num\et'",$entry[$num],"'\en";
945 \& if ($key ne "_$package" && defined %entry) {
946 \& print "\e%$key = (\en";
947 \& foreach $key (sort keys(%entry)) {
948 \& print " $key\et'",$entry{$key},"'\en";
957 Note that, even though the subroutine is compiled in package dumpvar, the
958 name of the subroutine is qualified so that it's name is inserted into package
961 Each programmer will, of course, have his or her own preferences in regards
962 to formatting, but there are some general guidelines that will make your
963 programs easier to read.
965 Just because you CAN do something a particular way doesn't mean that
966 you SHOULD do it that way.
968 is designed to give you several ways to do anything, so consider picking
969 the most readable one.
972 open(FOO,$foo) || die "Can't open $foo: $!";
976 die "Can't open $foo: $!" unless open(FOO,$foo);
978 because the second way hides the main point of the statement in a
982 print "Starting analysis\en" if $verbose;
986 $verbose && print "Starting analysis\en";
988 since the main point isn't whether the user typed -v or not.
990 Similarly, just because an operator lets you assume default arguments
991 doesn't mean that you have to make use of the defaults.
992 The defaults are there for lazy systems programmers writing one-shot
994 If you want your program to be readable, consider supplying the argument.
996 Don't go through silly contortions to exit a loop at the top or the
999 provides the "last" operator so you can exit in the middle.
1000 Just outdent it a little to make it more visible:
1014 Don't be afraid to use loop labels\*(--they're there to enhance readability as
1015 well as to allow multi-level loop breaks.
1018 For portability, when using features that may not be implemented on every
1019 machine, test the construct in an eval to see if it fails.
1021 Choose mnemonic indentifiers.
1029 switch, your script will be run under a debugging monitor.
1030 It will halt before the first executable statement and ask you for a
1033 Prints out a help message.
1036 Executes until it reaches the beginning of another statement.
1039 Executes until the next breakpoint is reached.
1043 Single step around subroutine call.
1044 .Ip "l min+incr" 12 4
1045 List incr+1 lines starting at min.
1046 If min is omitted, starts where last listing left off.
1047 If incr is omitted, previous value of incr is used.
1048 .Ip "l min-max" 12 4
1049 List lines in the indicated range.
1051 List just the indicated line.
1053 List incr+1 more lines after last printed line.
1054 .Ip "l subname" 12 4
1056 If it's a long subroutine it just lists the beginning.
1057 Use \*(L"l\*(R" to list more.
1059 List lines that have breakpoints or actions.
1061 Toggle trace mode on or off.
1064 If line is omitted, sets a breakpoint on the current line
1065 line that is about to be executed.
1066 Breakpoints may only be set on lines that begin an executable statement.
1067 .Ip "b subname" 12 4
1068 Set breakpoint at first executable line of subroutine.
1070 Lists the names of all subroutines.
1073 If line is omitted, deletes the breakpoint on the current line
1074 line that is about to be executed.
1076 Delete all breakpoints.
1078 Delete all line actions.
1079 .Ip "V package" 12 4
1080 List all variables in package.
1081 Default is main package.
1082 .Ip "a line command" 12 4
1083 Set an action for line.
1084 A multi-line command may be entered by backslashing the newlines.
1085 .Ip "< command" 12 4
1086 Set an action to happen before every debugger prompt.
1087 A multi-line command may be entered by backslashing the newlines.
1088 .Ip "> command" 12 4
1089 Set an action to happen after the prompt when you've just given a command
1090 to return to executing the script.
1091 A multi-line command may be entered by backslashing the newlines.
1093 Redo a debugging command.
1094 If number is omitted, redoes the previous command.
1095 .Ip "! -number" 12 4
1096 Redo the command that was that many commands ago.
1097 .Ip "H -number" 12 4
1098 Display last n commands.
1099 Only commands longer than one character are listed.
1100 If number is omitted, lists them all.
1104 Execute command as a perl statement.
1105 A missing semicolon will be supplied.
1107 Same as \*(L"print DB'OUT expr\*(R".
1108 The DB'OUT filehandle is opened to /dev/tty, regardless of where STDOUT
1109 may be redirected to.
1111 If you want to modify the debugger, copy perldb.pl from the perl library
1112 to your current directory and modify it as necessary.
1113 You can do some customization by setting up a .perldb file which contains
1114 initialization code.
1115 For instance, you could make aliases like these:
1118 $DBalias{'len'} = 's/^len(.*)/p length(\e$1)/';
1119 $DBalias{'stop'} = 's/^stop (at|in)/b/';
1121 's/^./p "\e$DBsub(\e$DBline):\et\e$DBline[\e$DBline]"/';
1124 .Sh "Setuid Scripts"
1126 is designed to make it easy to write secure setuid and setgid scripts.
1127 Unlike shells, which are based on multiple substitution passes on each line
1130 uses a more conventional evaluation scheme with fewer hidden \*(L"gotchas\*(R".
1131 Additionally, since the language has more built-in functionality, it
1132 has to rely less upon external (and possibly untrustworthy) programs to
1133 accomplish its purposes.
1135 In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
1136 insecure, but this kernel feature can be disabled.
1139 can emulate the setuid and setgid mechanism when it notices the otherwise
1140 useless setuid/gid bits on perl scripts.
1141 If the kernel feature isn't disabled,
1143 will complain loudly that your setuid script is insecure.
1144 You'll need to either disable the kernel setuid script feature, or put
1145 a C wrapper around the script.
1147 When perl is executing a setuid script, it takes special precautions to
1148 prevent you from falling into any obvious traps.
1149 (In some ways, a perl script is more secure than the corresponding
1151 Any command line argument, environment variable, or input is marked as
1152 \*(L"tainted\*(R", and may not be used, directly or indirectly, in any
1153 command that invokes a subshell, or in any command that modifies files,
1154 directories or processes.
1155 Any variable that is set within an expression that has previously referenced
1156 a tainted value also becomes tainted (even if it is logically impossible
1157 for the tainted value to influence the variable).
1162 $foo = shift; # $foo is tainted
1163 $bar = $foo,\'bar\'; # $bar is also tainted
1164 $xxx = <>; # Tainted
1165 $path = $ENV{\'PATH\'}; # Tainted, but see below
1166 $abc = \'abc\'; # Not tainted
1169 system "echo $foo"; # Insecure
1170 system "echo", $foo; # Secure (doesn't use sh)
1171 system "echo $bar"; # Insecure
1172 system "echo $abc"; # Insecure until PATH set
1175 $ENV{\'PATH\'} = \'/bin:/usr/bin\';
1176 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1178 $path = $ENV{\'PATH\'}; # Not tainted
1179 system "echo $abc"; # Is secure now!
1182 open(FOO,"$foo"); # OK
1183 open(FOO,">$foo"); # Not OK
1185 open(FOO,"echo $foo|"); # Not OK, but...
1186 open(FOO,"-|") || exec \'echo\', $foo; # OK
1188 $zzz = `echo $foo`; # Insecure, zzz tainted
1190 unlink $abc,$foo; # Insecure
1191 umask $foo; # Insecure
1194 exec "echo $foo"; # Insecure
1195 exec "echo", $foo; # Secure (doesn't use sh)
1196 exec "sh", \'-c\', $foo; # Considered secure, alas
1199 The taintedness is associated with each scalar value, so some elements
1200 of an array can be tainted, and others not.
1202 If you try to do something insecure, you will get a fatal error saying
1203 something like \*(L"Insecure dependency\*(R" or \*(L"Insecure PATH\*(R".
1204 Note that you can still write an insecure system call or exec,
1205 but only by explicity doing something like the last example above.
1206 You can also bypass the tainting mechanism by referencing
1209 presumes that if you reference a substring using $1, $2, etc, you knew
1210 what you were doing when you wrote the pattern:
1213 $ARGV[0] =~ /^\-P(\ew+)$/;
1214 $printer = $1; # Not tainted
1217 This is fairly secure since \ew+ doesn't match shell metacharacters.
1218 Use of .+ would have been insecure, but
1220 doesn't check for that, so you must be careful with your patterns.
1221 This is the ONLY mechanism for untainting user supplied filenames if you
1222 want to do file operations on them (unless you make $> equal to $<).
1224 It's also possible to get into trouble with other operations that don't care
1225 whether they use tainted values.
1226 Make judicious use of the file tests in dealing with any user-supplied
1228 When possible, do opens and such after setting $> = $<.
1230 doesn't prevent you from opening tainted filenames for reading, so be
1231 careful what you print out.
1232 The tainting mechanism is intended to prevent stupid mistakes, not to remove
1233 the need for thought.
1236 uses PATH in executing subprocesses, and in finding the script if \-S
1238 HOME or LOGDIR are used if chdir has no argument.
1242 uses no environment variables, except to make them available
1243 to the script being executed, and to child processes.
1244 However, scripts running setuid would do well to execute the following lines
1245 before doing anything else, just to keep people honest:
1249 $ENV{\'PATH\'} = \'/bin:/usr/bin\'; # or whatever you need
1250 $ENV{\'SHELL\'} = \'/bin/sh\' if $ENV{\'SHELL\'} ne \'\';
1251 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1255 Larry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
1257 /tmp/perl\-eXXXXXX temporary file for
1261 a2p awk to perl translator
1263 s2p sed to perl translator
1265 Compilation errors will tell you the line number of the error, with an
1266 indication of the next token or token type that was to be examined.
1267 (In the case of a script passed to
1273 is counted as one line.)
1275 Setuid scripts have additional constraints that can produce error messages
1276 such as \*(L"Insecure dependency\*(R".
1277 See the section on setuid scripts.
1281 users should take special note of the following:
1283 Semicolons are required after all simple statements in
1286 is not a statement delimiter.
1288 Curly brackets are required on ifs and whiles.
1290 Variables begin with $ or @ in
1293 Arrays index from 0 unless you set $[.
1294 Likewise string positions in substr() and index().
1296 You have to decide whether your array has numeric or string indices.
1298 Associative array values do not spring into existence upon mere reference.
1300 You have to decide whether you want to use string or numeric comparisons.
1302 Reading an input line does not split it for you. You get to split it yourself
1306 operator has different arguments.
1308 The current input line is normally in $_, not $0.
1309 It generally does not have the newline stripped.
1310 ($0 is initially the name of the program executed, then the last matched
1313 $<digit> does not refer to fields\*(--it refers to substrings matched by the last
1318 statement does not add field and record separators unless you set
1321 You must open your files before you print to them.
1323 The range operator is \*(L".\|.\*(R", not comma.
1324 (The comma operator works as in C.)
1326 The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
1327 (\*(L"~\*(R" is the one's complement operator, as in C.)
1329 The exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
1330 (\*(L"^\*(R" is the XOR operator, as in C.)
1332 The concatenation operator is \*(L".\*(R", not the null string.
1333 (Using the null string would render \*(L"/pat/ /pat/\*(R" unparsable,
1334 since the third slash would be interpreted as a division operator\*(--the
1335 tokener is in fact slightly context sensitive for operators like /, ?, and <.
1336 And in fact, . itself can be the beginning of a number.)
1344 The following variables work differently
1348 ARGC \h'|2.5i'$#ARGV
1350 FILENAME\h'|2.5i'$ARGV
1351 FNR \h'|2.5i'$. \- something
1352 FS \h'|2.5i'(whatever you like)
1353 NF \h'|2.5i'$#Fld, or some such
1358 RLENGTH \h'|2.5i'length($&)
1360 RSTART \h'|2.5i'length($\`)
1365 When in doubt, run the
1367 construct through a2p and see what it gives you.
1369 Cerebral C programmers should take note of the following:
1371 Curly brackets are required on ifs and whiles.
1373 You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
1384 There's no switch statement.
1386 Variables begin with $ or @ in
1389 Printf does not implement *.
1391 Comments begin with #, not /*.
1393 You can't take the address of anything.
1395 ARGV must be capitalized.
1397 The \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
1399 Signal handlers deal with signal names, not numbers.
1401 You can't subscript array values, only arrays (no $x = (1,2,3)[2];).
1405 programmers should take note of the following:
1407 Backreferences in substitutions use $ rather than \e.
1409 The pattern matching metacharacters (, ), and | do not have backslashes in front.
1411 The range operator is .\|. rather than comma.
1413 Sharp shell programmers should take note of the following:
1415 The backtick operator does variable interpretation without regard to the
1416 presence of single quotes in the command.
1418 The backtick operator does no translation of the return value, unlike csh.
1420 Shells (especially csh) do several levels of substitution on each command line.
1422 does substitution only in certain constructs such as double quotes,
1423 backticks, angle brackets and search patterns.
1425 Shells interpret scripts a little bit at a time.
1427 compiles the whole program before executing it.
1429 The arguments are available via @ARGV, not $1, $2, etc.
1431 The environment is not automatically made available as variables.
1435 is at the mercy of your machine's definitions of various operations
1436 such as type casting, atof() and sprintf().
1438 If your stdio requires an seek or eof between reads and writes on a particular
1442 While none of the built-in data types have any arbitrary size limits (apart
1443 from memory size), there are still a few arbitrary limits:
1444 a given identifier may not be longer than 255 characters;
1445 sprintf is limited on many machines to 128 characters per field (unless the format
1446 specifier is exactly %s);
1447 and no component of your PATH may be longer than 255 if you use \-S.
1450 actually stands for Pathologically Eclectic Rubbish Lister, but don't tell