1 ''' Beginning of part 4
2 ''' $Header: perl.man.4,v 3.0.1.4 89/12/21 20:12:39 lwall Locked $
4 ''' $Log: perl.man.4,v $
5 ''' Revision 3.0.1.4 89/12/21 20:12:39 lwall
6 ''' patch7: documented that package'filehandle works as well as $package'variable
7 ''' patch7: documented which identifiers are always in package main
9 ''' Revision 3.0.1.3 89/11/17 15:32:25 lwall
10 ''' patch5: fixed some manual typos and indent problems
11 ''' patch5: clarified difference between $! and $@
13 ''' Revision 3.0.1.2 89/11/11 04:46:40 lwall
14 ''' patch2: made some line breaks depend on troff vs. nroff
15 ''' patch2: clarified operation of ^ and $ when $* is false
17 ''' Revision 3.0.1.1 89/10/26 23:18:43 lwall
18 ''' patch1: documented the desirability of unnecessary parentheses
20 ''' Revision 3.0 89/10/18 15:21:55 lwall
25 operators have the following associativity and precedence:
28 nonassoc\h'|1i'print printf exec system sort reverse
29 \h'1.5i'chmod chown kill unlink utime die return
31 right\h'|1i'= += \-= *= etc.
38 nonassoc\h'|1i'== != eq ne
39 nonassoc\h'|1i'< > <= >= lt gt le ge
40 nonassoc\h'|1i'chdir exit eval reset sleep rand umask
41 nonassoc\h'|1i'\-r \-w \-x etc.
46 right\h'|1i'! ~ and unary minus
48 nonassoc\h'|1i'++ \-\|\-
49 left\h'|1i'\*(L'(\*(R'
52 As mentioned earlier, if any list operator (print, etc.) or
53 any unary operator (chdir, etc.)
54 is followed by a left parenthesis as the next token on the same line,
55 the operator and arguments within parentheses are taken to
56 be of highest precedence, just like a normal function call.
60 chdir $foo || die;\h'|3i'# (chdir $foo) || die
61 chdir($foo) || die;\h'|3i'# (chdir $foo) || die
62 chdir ($foo) || die;\h'|3i'# (chdir $foo) || die
63 chdir +($foo) || die;\h'|3i'# (chdir $foo) || die
65 but, because * is higher precedence than ||:
67 chdir $foo * 20;\h'|3i'# chdir ($foo * 20)
68 chdir($foo) * 20;\h'|3i'# (chdir $foo) * 20
69 chdir ($foo) * 20;\h'|3i'# (chdir $foo) * 20
70 chdir +($foo) * 20;\h'|3i'# chdir ($foo * 20)
72 rand 10 * 20;\h'|3i'# rand (10 * 20)
73 rand(10) * 20;\h'|3i'# (rand 10) * 20
74 rand (10) * 20;\h'|3i'# (rand 10) * 20
75 rand +(10) * 20;\h'|3i'# rand (10 * 20)
78 In the absence of parentheses,
79 the precedence of list operators such as print, sort or chmod is
80 either very high or very low depending on whether you look at the left
81 side of operator or the right side of it.
85 @ary = (1, 3, sort 4, 2);
86 print @ary; # prints 1324
89 the commas on the right of the sort are evaluated before the sort, but
90 the commas on the left are evaluated after.
91 In other words, list operators tend to gobble up all the arguments that
92 follow them, and then act like a simple term with regard to the preceding
94 Note that you have to be careful with parens:
98 # These evaluate exit before doing the print:
99 print($foo, exit); # Obviously not what you want.
100 print $foo, exit; # Nor is this.
103 # These do the print before evaluating exit:
104 (print $foo), exit; # This is what you want.
105 print($foo), exit; # Or this.
106 print ($foo), exit; # Or even this.
110 print ($foo & 255) + 1, "\en";
113 probably doesn't do what you expect at first glance.
115 A subroutine may be declared as follows:
122 Any arguments passed to the routine come in as array @_,
123 that is ($_[0], $_[1], .\|.\|.).
124 The array @_ is a local array, but its values are references to the
125 actual scalar parameters.
126 The return value of the subroutine is the value of the last expression
127 evaluated, and can be either an array value or a scalar value.
128 Alternately, a return statement may be used to specify the returned value and
130 To create local variables see the
134 A subroutine is called using the
136 operator or the & operator.
143 local($max) = pop(@_);
145 $max = $foo \|if \|$max < $foo;
151 $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
156 # get a line, combining continuation lines
157 # that start with whitespace
159 $thisline = $lookahead;
160 line: while ($lookahead = <STDIN>) {
161 if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
162 $thisline \|.= \|$lookahead;
171 $lookahead = <STDIN>; # get first line
172 while ($_ = do get_line(\|)) {
179 Use array assignment to a local list to name your formal arguments:
182 local($key, $value) = @_;
183 $foo{$key} = $value unless $foo{$key};
187 This also has the effect of turning call-by-reference into call-by-value,
188 since the assignment copies the values.
190 Subroutines may be called recursively.
191 If a subroutine is called using the & form, the argument list is optional.
192 If omitted, no @_ array is set up for the subroutine; the @_ array at the
193 time of the call is visible to subroutine instead.
196 do foo(1,2,3); # pass three arguments
197 &foo(1,2,3); # the same
199 do foo(); # pass a null list
201 &foo; # pass no arguments--more efficient
204 .Sh "Passing By Reference"
205 Sometimes you don't want to pass the value of an array to a subroutine but
206 rather the name of it, so that the subroutine can modify the global copy
207 of it rather than working with a local copy.
208 In perl you can refer to all the objects of a particular name by prefixing
209 the name with a star: *foo.
210 When evaluated, it produces a scalar value that represents all the objects
212 When assigned to within a local() operation, it causes the name mentioned
213 to refer to whatever * value was assigned to it.
218 local(*someary) = @_;
219 foreach $elem (@someary) {
227 Assignment to *name is currently recommended only inside a local().
228 You can actually assign to *name anywhere, but the previous referent of
229 *name may be stranded forever.
230 This may or may not bother you.
232 Note that scalars are already passed by reference, so you can modify scalar
233 arguments without using this mechanism by referring explicitly to the $_[nnn]
235 You can modify all the elements of an array by passing all the elements
236 as scalars, but you have to use the * mechanism to push, pop or change the
238 The * mechanism will probably be more efficient in any case.
240 Since a *name value contains unprintable binary data, if it is used as
241 an argument in a print, or as a %s argument in a printf or sprintf, it
242 then has the value '*name', just so it prints out pretty.
243 .Sh "Regular Expressions"
244 The patterns used in pattern matching are regular expressions such as
245 those supplied in the Version 8 regexp routines.
246 (In fact, the routines are derived from Henry Spencer's freely redistributable
247 reimplementation of the V8 routines.)
248 In addition, \ew matches an alphanumeric character (including \*(L"_\*(R") and \eW a nonalphanumeric.
249 Word boundaries may be matched by \eb, and non-boundaries by \eB.
250 A whitespace character is matched by \es, non-whitespace by \eS.
251 A numeric character is matched by \ed, non-numeric by \eD.
252 You may use \ew, \es and \ed within character classes.
253 Also, \en, \er, \ef, \et and \eNNN have their normal interpretations.
254 Within character classes \eb represents backspace rather than a word boundary.
255 Alternatives may be separated by |.
256 The bracketing construct \|(\ .\|.\|.\ \|) may also be used, in which case \e<digit>
257 matches the digit'th substring, where digit can range from 1 to 9.
258 (Outside of the pattern, always use $ instead of \e in front of the digit.
259 The scope of $<digit> (and $\`, $& and $\')
260 extends to the end of the enclosing BLOCK or eval string, or to
261 the next pattern match with subexpressions.
262 The \e<digit> notation sometimes works outside the current pattern, but should
264 $+ returns whatever the last bracket match matched.
265 $& returns the entire matched string.
266 ($0 normally returns the same thing, but don't depend on it.)
267 $\` returns everything before the matched string.
268 $\' returns everything after the matched string.
272 s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/; # swap first two words
275 if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
282 By default, the ^ character is only guaranteed to match at the beginning
284 the $ character only at the end (or before the newline at the end)
287 does certain optimizations with the assumption that the string contains
289 The behavior of ^ and $ on embedded newlines will be inconsistent.
290 You may, however, wish to treat a string as a multi-line buffer, such that
291 the ^ will match after any newline within the string, and $ will match
293 At the cost of a little more overhead, you can do this by setting the variable
295 Setting it back to 0 makes
297 revert to its old behavior.
299 To facilitate multi-line substitutions, the . character never matches a newline
301 In particular, the following leaves a newline on the $_ string:
305 s/.*(some_string).*/$1/;
307 If the newline is unwanted, try one of
309 s/.*(some_string).*\en/$1/;
310 s/.*(some_string)[^\e000]*/$1/;
311 s/.*(some_string)(.|\en)*/$1/;
312 chop; s/.*(some_string).*/$1/;
313 /(some_string)/ && ($_ = $1);
316 Any item of a regular expression may be followed with digits in curly brackets
317 of the form {n,m}, where n gives the minimum number of times to match the item
318 and m gives the maximum.
319 The form {n} is equivalent to {n,n} and matches exactly n times.
320 The form {n,} matches n or more times.
321 (If a curly bracket occurs in any other context, it is treated as a regular
323 The * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
325 There is no limit to the size of n or m, but large numbers will chew up
328 You will note that all backslashed metacharacters in
331 such as \eb, \ew, \en.
332 Unlike some other regular expression languages, there are no backslashed
333 symbols that aren't alphanumeric.
334 So anything that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} is always
335 interpreted as a literal character, not a metacharacter.
336 This makes it simple to quote a string that you want to use for a pattern
337 but that you are afraid might contain metacharacters.
338 Simply quote all the non-alphanumeric characters:
341 $pattern =~ s/(\eW)/\e\e$1/g;
345 Output record formats for use with the
347 operator may declared as follows:
356 If name is omitted, format \*(L"STDOUT\*(R" is defined.
357 FORMLIST consists of a sequence of lines, each of which may be of one of three
362 A \*(L"picture\*(R" line giving the format for one output line.
364 An argument line supplying values to plug into a picture line.
366 Picture lines are printed exactly as they look, except for certain fields
367 that substitute values into the line.
368 Each picture field starts with either @ or ^.
369 The @ field (not to be confused with the array marker @) is the normal
370 case; ^ fields are used
371 to do rudimentary multi-line text block filling.
372 The length of the field is supplied by padding out the field
373 with multiple <, >, or | characters to specify, respectively, left justification,
374 right justification, or centering.
375 If any of the values supplied for these fields contains a newline, only
376 the text up to the newline is printed.
377 The special field @* can be used for printing multi-line values.
378 It should appear by itself on a line.
380 The values are specified on the following line, in the same order as
382 The values should be separated by commas.
384 Picture fields that begin with ^ rather than @ are treated specially.
385 The value supplied must be a scalar variable name which contains a text
388 puts as much text as it can into the field, and then chops off the front
389 of the string so that the next time the variable is referenced,
390 more of the text can be printed.
391 Normally you would use a sequence of fields in a vertical stack to print
393 If you like, you can end the final field with .\|.\|., which will appear in the
394 output if the text was too long to appear in its entirety.
395 You can change which characters are legal to break on by changing the
396 variable $: to a list of the desired characters.
398 Since use of ^ fields can produce variable length records if the text to be
399 formatted is short, you can suppress blank lines by putting the tilde (~)
400 character anywhere in the line.
401 (Normally you should put it in the front if possible, for visibility.)
402 The tilde will be translated to a space upon output.
403 If you put a second tilde contiguous to the first, the line will be repeated
404 until all the fields on the line are exhausted.
405 (If you use a field of the @ variety, the expression you supply had better
406 not give the same value every time forever!)
415 # a report on the /etc/passwd file
418 Name Login Office Uid Gid Home
419 ------------------------------------------------------------------
422 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
423 $name, $login, $office,$uid,$gid, $home
427 # a report from a bug report form
430 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
432 ------------------------------------------------------------------
435 Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
437 Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
438 \& $index, $description
439 Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
440 \& $priority, $date, $description
441 From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
442 \& $from, $description
443 Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
444 \& $programmer, $description
445 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
447 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
449 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
451 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
453 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<...
461 It is possible to intermix prints with writes on the same output channel,
462 but you'll have to handle $\- (lines left on the page) yourself.
464 If you are printing lots of fields that are usually blank, you should consider
465 using the reset operator between records.
466 Not only is it more efficient, but it can prevent the bug of adding another
467 field and forgetting to zero it.
468 .Sh "Interprocess Communication"
469 The IPC facilities of perl are built on the Berkeley socket mechanism.
470 If you don't have sockets, you can ignore this section.
471 The calls have the same names as the corresponding system calls,
472 but the arguments tend to differ, for two reasons.
473 First, perl file handles work differently than C file descriptors.
474 Second, perl already knows the length of its strings, so you don't need
475 to pass that information.
476 Here is a sample client (untested):
479 ($them,$port) = @ARGV;
480 $port = 2345 unless $port;
481 $them = 'localhost' unless $them;
483 $SIG{'INT'} = 'dokill';
484 sub dokill { kill 9,$child if $child; }
486 do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
488 $sockaddr = 'S n a4 x8';
489 chop($hostname = `hostname`);
491 ($name, $aliases, $proto) = getprotobyname('tcp');
492 ($name, $aliases, $port) = getservbyname($port, 'tcp')
493 unless $port =~ /^\ed+$/;;
495 ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
498 ($name, $aliases, $type, $len, $thisaddr) =
499 gethostbyname($hostname);
501 ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
503 $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
504 $that = pack($sockaddr, &AF_INET, $port, $thataddr);
506 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
507 bind(S, $this) || die "bind: $!";
508 connect(S, $that) || die "connect: $!";
510 select(S); $| = 1; select(stdout);
530 $port = 2345 unless $port;
532 do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
534 $sockaddr = 'S n a4 x8';
536 ($name, $aliases, $proto) = getprotobyname('tcp');
537 ($name, $aliases, $port) = getservbyname($port, 'tcp')
538 unless $port =~ /^\ed+$/;;
540 $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
542 select(NS); $| = 1; select(stdout);
544 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
545 bind(S, $this) || die "bind: $!";
546 listen(S, 5) || die "connect: $!";
548 select(S); $| = 1; select(stdout);
551 print "Listening again\en";
552 ($addr = accept(NS,S)) || die $!;
553 print "accept ok\en";
555 ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
556 @inetaddr = unpack('C4',$inetaddr);
557 print "$af $port @inetaddr\en";
566 .Sh "Predefined Names"
567 The following names have special meaning to
569 I could have used alphabetic symbols for some of these, but I didn't want
570 to take the chance that someone would say reset \*(L"a\-zA\-Z\*(R" and wipe them all
572 You'll just have to suffer along with these silly symbols.
573 Most of them have reasonable mnemonics, or analogues in one of the shells.
575 The default input and pattern-searching space.
576 The following pairs are equivalent:
580 while (<>) {\|.\|.\|. # only equivalent in while!
581 while ($_ = <>) {\|.\|.\|.
585 $_ \|=~ \|/\|^Subject:/
596 (Mnemonic: underline is understood in certain operations.)
598 The current input line number of the last filehandle that was read.
600 Remember that only an explicit close on the filehandle resets the line number.
601 Since <> never does an explicit close, line numbers increase across ARGV files
602 (but see examples under eof).
603 (Mnemonic: many programs use . to mean the current line number.)
605 The input record separator, newline by default.
608 RS variable, including treating blank lines as delimiters
609 if set to the null string.
610 If set to a value longer than one character, only the first character is used.
611 (Mnemonic: / is used to delimit line boundaries when quoting poetry.)
613 The output field separator for the print operator.
614 Ordinarily the print operator simply prints out the comma separated fields
616 In order to get behavior more like
618 set this variable as you would set
620 OFS variable to specify what is printed between fields.
621 (Mnemonic: what is printed when there is a , in your print statement.)
623 This is like $, except that it applies to array values interpolated into
624 a double-quoted string (or similar interpreted string).
626 (Mnemonic: obvious, I think.)
628 The output record separator for the print operator.
629 Ordinarily the print operator simply prints out the comma separated fields
630 you specify, with no trailing newline or record separator assumed.
631 In order to get behavior more like
633 set this variable as you would set
635 ORS variable to specify what is printed at the end of the print.
636 (Mnemonic: you set $\e instead of adding \en at the end of the print.
637 Also, it's just like /, but it's what you get \*(L"back\*(R" from
640 The output format for printed numbers.
641 This variable is a half-hearted attempt to emulate
644 There are times, however, when
648 have differing notions of what
650 Also, the initial value is %.20g rather than %.6g, so you need to set $#
654 (Mnemonic: # is the number sign.)
656 The current page number of the currently selected output channel.
657 (Mnemonic: % is page number in nroff.)
659 The current page length (printable lines) of the currently selected output
662 (Mnemonic: = has horizontal lines.)
664 The number of lines left on the page of the currently selected output channel.
665 (Mnemonic: lines_on_page \- lines_printed.)
667 The name of the current report format for the currently selected output
669 (Mnemonic: brother to $^.)
671 The name of the current top-of-page format for the currently selected output
673 (Mnemonic: points to top of page.)
675 If set to nonzero, forces a flush after every write or print on the currently
676 selected output channel.
680 will typically be line buffered if output is to the
681 terminal and block buffered otherwise.
682 Setting this variable is useful primarily when you are outputting to a pipe,
683 such as when you are running a
685 script under rsh and want to see the
686 output as it's happening.
687 (Mnemonic: when you want your pipes to be piping hot.)
689 The process number of the
692 (Mnemonic: same as shells.)
694 The status returned by the last pipe close, backtick (\`\`) command or
697 Note that this is the status word returned by the wait() system
698 call, so the exit value of the subprocess is actually ($? >> 8).
699 $? & 255 gives which signal, if any, the process died from, and whether
700 there was a core dump.
701 (Mnemonic: similar to sh and ksh.)
703 The string matched by the last pattern match (not counting any matches hidden
704 within a BLOCK or eval enclosed by the current BLOCK).
705 (Mnemonic: like & in some editors.)
707 The string preceding whatever was matched by the last pattern match
708 (not counting any matches hidden within a BLOCK or eval enclosed by the current
710 (Mnemonic: \` often precedes a quoted string.)
712 The string following whatever was matched by the last pattern match
713 (not counting any matches hidden within a BLOCK or eval enclosed by the current
715 (Mnemonic: \' often follows a quoted string.)
722 print "$\`:$&:$\'\en"; # prints abc:def:ghi
726 The last bracket matched by the last search pattern.
727 This is useful if you don't know which of a set of alternative patterns
732 /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
735 (Mnemonic: be positive and forward looking.)
737 Set to 1 to do multiline matching within a string, 0 to tell
739 that it can assume that strings contain a single line, for the purpose
740 of optimizing pattern matches.
741 Pattern matches on strings containing multiple newlines can produce confusing
742 results when $* is 0.
744 (Mnemonic: * matches multiple things.)
746 Contains the name of the file containing the
748 script being executed.
749 The value should be copied elsewhere before any pattern matching happens, which
751 (Mnemonic: same as sh and ksh.)
753 Contains the subpattern from the corresponding set of parentheses in the last
754 pattern matched, not counting patterns matched in nested blocks that have
756 (Mnemonic: like \edigit.)
758 The index of the first element in an array, and of the first character in
760 Default is 0, but you could set it to 1 to make
765 when subscripting and when evaluating the index() and substr() functions.
766 (Mnemonic: [ begins subscripts.)
768 The string printed out when you say \*(L"perl -v\*(R".
769 It can be used to determine at the beginning of a script whether the perl
770 interpreter executing the script is in the right range of versions.
775 # see if getc is available
776 ($version,$patchlevel) =
777 $] =~ /(\ed+\e.\ed+).*\enPatch level: (\ed+)/;
778 print STDERR "(No filename completion available.)\en"
779 if $version * 1000 + $patchlevel < 2016;
782 (Mnemonic: Is this version of perl in the right bracket?)
784 The subscript separator for multi-dimensional array emulation.
785 If you refer to an associative array element as
791 $foo{join($;, $a, $b, $c)}
795 @foo{$a,$b,$c} # a slice--note the @
799 ($foo{$a},$foo{$b},$foo{$c})
802 Default is "\e034", the same as SUBSEP in
804 Note that if your keys contain binary data there might not be any safe
806 (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
807 Yeah, I know, it's pretty lame, but $, is already taken for something more
810 If used in a numeric context, yields the current value of errno, with all the
812 (This means that you shouldn't depend on the value of $! to be anything
813 in particular unless you've gotten a specific error return indicating a
815 If used in a string context, yields the corresponding system error string.
816 You can assign to $! in order to set errno
817 if, for instance, you want $! to return the string for error n, or you want
818 to set the exit value for the die operator.
819 (Mnemonic: What just went bang?)
821 The perl syntax error message from the last eval command.
822 If null, the last eval parsed and executed correctly (although the operations
823 you invoked may have failed in the normal fashion).
824 (Mnemonic: Where was the syntax error \*(L"at\*(R"?)
826 The real uid of this process.
827 (Mnemonic: it's the uid you came FROM, if you're running setuid.)
829 The effective uid of this process.
834 $< = $>; # set real uid to the effective uid
835 ($<,$>) = ($>,$<); # swap real and effective uid
838 (Mnemonic: it's the uid you went TO, if you're running setuid.)
839 Note: $< and $> can only be swapped on machines supporting setreuid().
841 The real gid of this process.
842 If you are on a machine that supports membership in multiple groups
843 simultaneously, gives a space separated list of groups you are in.
844 The first number is the one returned by getgid(), and the subsequent ones
845 by getgroups(), one of which may be the same as the first number.
846 (Mnemonic: parentheses are used to GROUP things.
847 The real gid is the group you LEFT, if you're running setgid.)
849 The effective gid of this process.
850 If you are on a machine that supports membership in multiple groups
851 simultaneously, gives a space separated list of groups you are in.
852 The first number is the one returned by getegid(), and the subsequent ones
853 by getgroups(), one of which may be the same as the first number.
854 (Mnemonic: parentheses are used to GROUP things.
855 The effective gid is the group that's RIGHT for you, if you're running setgid.)
857 Note: $<, $>, $( and $) can only be set on machines that support the
858 corresponding set[re][ug]id() routine.
859 $( and $) can only be swapped on machines supporting setregid().
861 The current set of characters after which a string may be broken to
862 fill continuation fields (starting with ^) in a format.
863 Default is "\ \en-", to break on whitespace or hyphens.
864 (Mnemonic: a \*(L"colon\*(R" in poetry is a part of a line.)
866 The array ARGV contains the command line arguments intended for the script.
867 Note that $#ARGV is the generally number of arguments minus one, since
868 $ARGV[0] is the first argument, NOT the command name.
869 See $0 for the command name.
871 The array INC contains the list of places to look for
874 evaluated by the \*(L"do EXPR\*(R" command.
875 It initially consists of the arguments to any
877 command line switches, followed
880 library, probably \*(L"/usr/local/lib/perl\*(R".
882 The associative array ENV contains your current environment.
883 Setting a value in ENV changes the environment for child processes.
885 The associative array SIG is used to set signal handlers for various signals.
890 sub handler { # 1st argument is signal name
892 print "Caught a SIG$sig\-\|\-shutting down\en";
897 $SIG{\'INT\'} = \'handler\';
898 $SIG{\'QUIT\'} = \'handler\';
900 $SIG{\'INT\'} = \'DEFAULT\'; # restore default action
901 $SIG{\'QUIT\'} = \'IGNORE\'; # ignore SIGQUIT
904 The SIG array only contains values for the signals actually set within
907 Perl provides a mechanism for alternate namespaces to protect packages from
908 stomping on each others variables.
909 By default, a perl script starts compiling into the package known as \*(L"main\*(R".
912 declaration, you can switch namespaces.
913 The scope of the package declaration is from the declaration itself to the end
914 of the enclosing block (the same scope as the local() operator).
915 Typically it would be the first declaration in a file to be included by
916 the \*(L"do FILE\*(R" operator.
917 You can switch into a package in more than one place; it merely influences
918 which symbol table is used by the compiler for the rest of that block.
919 You can refer to variables and filehandles in other packages by prefixing
920 the identifier with the package name and a single quote.
921 If the package name is null, the \*(L"main\*(R" package as assumed.
923 Only identifiers starting with letters are stored in the packages symbol
925 All other symbols are kept in package \*(L"main\*(R".
926 In addition, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC
927 and SIG are forced to be in package \*(L"main\*(R", even when used for
928 other purposes than their built-in one.
929 Note also that, if you have a package called \*(L"m\*(R", \*(L"s\*(R"
930 or \*(L"y\*(R", the you can't use the qualified form of an identifier since it
931 will be interpreted instead as a pattern match, a substitution
934 Eval'ed strings are compiled in the package in which the eval was compiled
936 (Assignments to $SIG{}, however, assume the signal handler specified is in the
938 Qualify the signal handler name if you wish to have a signal handler in
940 For an example, examine perldb.pl in the perl library.
941 It initially switches to the DB package so that the debugger doesn't interfere
942 with variables in the script you are trying to debug.
943 At various points, however, it temporarily switches back to the main package
944 to evaluate various expressions in the context of the main package.
946 The symbol table for a package happens to be stored in the associative array
947 of that name prepended with an underscore.
948 The value in each entry of the associative array is
949 what you are referring to when you use the *name notation.
950 In fact, the following have the same effect (in package main, anyway),
951 though the first is more
952 efficient because it does the symbol table lookups at compile time:
957 local($_main{'foo'}) = $_main{'bar'};
960 You can use this to print out all the variables in a package, for instance.
961 Here is dumpvar.pl from the perl library:
968 \& local(*stab) = eval("*_$package");
969 \& while (($key,$val) = each(%stab)) {
971 \& local(*entry) = $val;
972 \& if (defined $entry) {
973 \& print "\e$$key = '$entry'\en";
976 \& if (defined @entry) {
977 \& print "\e@$key = (\en";
978 \& foreach $num ($[ .. $#entry) {
979 \& print " $num\et'",$entry[$num],"'\en";
984 \& if ($key ne "_$package" && defined %entry) {
985 \& print "\e%$key = (\en";
986 \& foreach $key (sort keys(%entry)) {
987 \& print " $key\et'",$entry{$key},"'\en";
996 Note that, even though the subroutine is compiled in package dumpvar, the
997 name of the subroutine is qualified so that its name is inserted into package
1000 Each programmer will, of course, have his or her own preferences in regards
1001 to formatting, but there are some general guidelines that will make your
1002 programs easier to read.
1004 Just because you CAN do something a particular way doesn't mean that
1005 you SHOULD do it that way.
1007 is designed to give you several ways to do anything, so consider picking
1008 the most readable one.
1011 open(FOO,$foo) || die "Can't open $foo: $!";
1015 die "Can't open $foo: $!" unless open(FOO,$foo);
1017 because the second way hides the main point of the statement in a
1021 print "Starting analysis\en" if $verbose;
1025 $verbose && print "Starting analysis\en";
1027 since the main point isn't whether the user typed -v or not.
1029 Similarly, just because an operator lets you assume default arguments
1030 doesn't mean that you have to make use of the defaults.
1031 The defaults are there for lazy systems programmers writing one-shot
1033 If you want your program to be readable, consider supplying the argument.
1035 Along the same lines, just because you
1037 omit parentheses in many places doesn't mean that you ought to:
1040 return print reverse sort num values array;
1041 return print(reverse(sort num (values(%array))));
1044 When in doubt, parenthesize.
1045 At the very least it will let some poor schmuck bounce on the % key in vi.
1047 Don't go through silly contortions to exit a loop at the top or the
1050 provides the "last" operator so you can exit in the middle.
1051 Just outdent it a little to make it more visible:
1065 Don't be afraid to use loop labels\*(--they're there to enhance readability as
1066 well as to allow multi-level loop breaks.
1069 For portability, when using features that may not be implemented on every
1070 machine, test the construct in an eval to see if it fails.
1071 If you know what version or patchlevel a particular feature was implemented,
1072 you can test $] to see if it will be there.
1074 Choose mnemonic identifiers.
1082 switch, your script will be run under a debugging monitor.
1083 It will halt before the first executable statement and ask you for a
1086 Prints out a help message.
1089 Executes until it reaches the beginning of another statement.
1092 Executes until the next breakpoint is reached.
1096 Single step around subroutine call.
1097 .Ip "l min+incr" 12 4
1098 List incr+1 lines starting at min.
1099 If min is omitted, starts where last listing left off.
1100 If incr is omitted, previous value of incr is used.
1101 .Ip "l min-max" 12 4
1102 List lines in the indicated range.
1104 List just the indicated line.
1106 List incr+1 more lines after last printed line.
1107 .Ip "l subname" 12 4
1109 If it's a long subroutine it just lists the beginning.
1110 Use \*(L"l\*(R" to list more.
1112 List lines that have breakpoints or actions.
1114 Toggle trace mode on or off.
1117 If line is omitted, sets a breakpoint on the current line
1118 line that is about to be executed.
1119 Breakpoints may only be set on lines that begin an executable statement.
1120 .Ip "b subname" 12 4
1121 Set breakpoint at first executable line of subroutine.
1123 Lists the names of all subroutines.
1126 If line is omitted, deletes the breakpoint on the current line
1127 line that is about to be executed.
1129 Delete all breakpoints.
1131 Delete all line actions.
1132 .Ip "V package" 12 4
1133 List all variables in package.
1134 Default is main package.
1135 .Ip "a line command" 12 4
1136 Set an action for line.
1137 A multi-line command may be entered by backslashing the newlines.
1138 .Ip "< command" 12 4
1139 Set an action to happen before every debugger prompt.
1140 A multi-line command may be entered by backslashing the newlines.
1141 .Ip "> command" 12 4
1142 Set an action to happen after the prompt when you've just given a command
1143 to return to executing the script.
1144 A multi-line command may be entered by backslashing the newlines.
1146 Redo a debugging command.
1147 If number is omitted, redoes the previous command.
1148 .Ip "! -number" 12 4
1149 Redo the command that was that many commands ago.
1150 .Ip "H -number" 12 4
1151 Display last n commands.
1152 Only commands longer than one character are listed.
1153 If number is omitted, lists them all.
1157 Execute command as a perl statement.
1158 A missing semicolon will be supplied.
1160 Same as \*(L"print DB'OUT expr\*(R".
1161 The DB'OUT filehandle is opened to /dev/tty, regardless of where STDOUT
1162 may be redirected to.
1164 If you want to modify the debugger, copy perldb.pl from the perl library
1165 to your current directory and modify it as necessary.
1166 You can do some customization by setting up a .perldb file which contains
1167 initialization code.
1168 For instance, you could make aliases like these:
1171 $DBalias{'len'} = 's/^len(.*)/p length(\e$1)/';
1172 $DBalias{'stop'} = 's/^stop (at|in)/b/';
1174 's/^./p "\e$DBsub(\e$DBline):\et\e$DBline[\e$DBline]"/';
1177 .Sh "Setuid Scripts"
1179 is designed to make it easy to write secure setuid and setgid scripts.
1180 Unlike shells, which are based on multiple substitution passes on each line
1183 uses a more conventional evaluation scheme with fewer hidden \*(L"gotchas\*(R".
1184 Additionally, since the language has more built-in functionality, it
1185 has to rely less upon external (and possibly untrustworthy) programs to
1186 accomplish its purposes.
1188 In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
1189 insecure, but this kernel feature can be disabled.
1192 can emulate the setuid and setgid mechanism when it notices the otherwise
1193 useless setuid/gid bits on perl scripts.
1194 If the kernel feature isn't disabled,
1196 will complain loudly that your setuid script is insecure.
1197 You'll need to either disable the kernel setuid script feature, or put
1198 a C wrapper around the script.
1200 When perl is executing a setuid script, it takes special precautions to
1201 prevent you from falling into any obvious traps.
1202 (In some ways, a perl script is more secure than the corresponding
1204 Any command line argument, environment variable, or input is marked as
1205 \*(L"tainted\*(R", and may not be used, directly or indirectly, in any
1206 command that invokes a subshell, or in any command that modifies files,
1207 directories or processes.
1208 Any variable that is set within an expression that has previously referenced
1209 a tainted value also becomes tainted (even if it is logically impossible
1210 for the tainted value to influence the variable).
1215 $foo = shift; # $foo is tainted
1216 $bar = $foo,\'bar\'; # $bar is also tainted
1217 $xxx = <>; # Tainted
1218 $path = $ENV{\'PATH\'}; # Tainted, but see below
1219 $abc = \'abc\'; # Not tainted
1222 system "echo $foo"; # Insecure
1223 system "echo", $foo; # Secure (doesn't use sh)
1224 system "echo $bar"; # Insecure
1225 system "echo $abc"; # Insecure until PATH set
1228 $ENV{\'PATH\'} = \'/bin:/usr/bin\';
1229 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1231 $path = $ENV{\'PATH\'}; # Not tainted
1232 system "echo $abc"; # Is secure now!
1235 open(FOO,"$foo"); # OK
1236 open(FOO,">$foo"); # Not OK
1238 open(FOO,"echo $foo|"); # Not OK, but...
1239 open(FOO,"-|") || exec \'echo\', $foo; # OK
1241 $zzz = `echo $foo`; # Insecure, zzz tainted
1243 unlink $abc,$foo; # Insecure
1244 umask $foo; # Insecure
1247 exec "echo $foo"; # Insecure
1248 exec "echo", $foo; # Secure (doesn't use sh)
1249 exec "sh", \'-c\', $foo; # Considered secure, alas
1252 The taintedness is associated with each scalar value, so some elements
1253 of an array can be tainted, and others not.
1255 If you try to do something insecure, you will get a fatal error saying
1256 something like \*(L"Insecure dependency\*(R" or \*(L"Insecure PATH\*(R".
1257 Note that you can still write an insecure system call or exec,
1258 but only by explicitly doing something like the last example above.
1259 You can also bypass the tainting mechanism by referencing
1262 presumes that if you reference a substring using $1, $2, etc, you knew
1263 what you were doing when you wrote the pattern:
1266 $ARGV[0] =~ /^\-P(\ew+)$/;
1267 $printer = $1; # Not tainted
1270 This is fairly secure since \ew+ doesn't match shell metacharacters.
1271 Use of .+ would have been insecure, but
1273 doesn't check for that, so you must be careful with your patterns.
1274 This is the ONLY mechanism for untainting user supplied filenames if you
1275 want to do file operations on them (unless you make $> equal to $<).
1277 It's also possible to get into trouble with other operations that don't care
1278 whether they use tainted values.
1279 Make judicious use of the file tests in dealing with any user-supplied
1281 When possible, do opens and such after setting $> = $<.
1283 doesn't prevent you from opening tainted filenames for reading, so be
1284 careful what you print out.
1285 The tainting mechanism is intended to prevent stupid mistakes, not to remove
1286 the need for thought.
1289 uses PATH in executing subprocesses, and in finding the script if \-S
1291 HOME or LOGDIR are used if chdir has no argument.
1295 uses no environment variables, except to make them available
1296 to the script being executed, and to child processes.
1297 However, scripts running setuid would do well to execute the following lines
1298 before doing anything else, just to keep people honest:
1302 $ENV{\'PATH\'} = \'/bin:/usr/bin\'; # or whatever you need
1303 $ENV{\'SHELL\'} = \'/bin/sh\' if $ENV{\'SHELL\'} ne \'\';
1304 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1308 Larry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
1310 /tmp/perl\-eXXXXXX temporary file for
1314 a2p awk to perl translator
1316 s2p sed to perl translator
1318 Compilation errors will tell you the line number of the error, with an
1319 indication of the next token or token type that was to be examined.
1320 (In the case of a script passed to
1326 is counted as one line.)
1328 Setuid scripts have additional constraints that can produce error messages
1329 such as \*(L"Insecure dependency\*(R".
1330 See the section on setuid scripts.
1334 users should take special note of the following:
1336 Semicolons are required after all simple statements in
1339 is not a statement delimiter.
1341 Curly brackets are required on ifs and whiles.
1343 Variables begin with $ or @ in
1346 Arrays index from 0 unless you set $[.
1347 Likewise string positions in substr() and index().
1349 You have to decide whether your array has numeric or string indices.
1351 Associative array values do not spring into existence upon mere reference.
1353 You have to decide whether you want to use string or numeric comparisons.
1355 Reading an input line does not split it for you. You get to split it yourself
1359 operator has different arguments.
1361 The current input line is normally in $_, not $0.
1362 It generally does not have the newline stripped.
1363 ($0 is initially the name of the program executed, then the last matched
1366 $<digit> does not refer to fields\*(--it refers to substrings matched by the last
1371 statement does not add field and record separators unless you set
1374 You must open your files before you print to them.
1376 The range operator is \*(L".\|.\*(R", not comma.
1377 (The comma operator works as in C.)
1379 The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
1380 (\*(L"~\*(R" is the one's complement operator, as in C.)
1382 The exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
1383 (\*(L"^\*(R" is the XOR operator, as in C.)
1385 The concatenation operator is \*(L".\*(R", not the null string.
1386 (Using the null string would render \*(L"/pat/ /pat/\*(R" unparsable,
1387 since the third slash would be interpreted as a division operator\*(--the
1388 tokener is in fact slightly context sensitive for operators like /, ?, and <.
1389 And in fact, . itself can be the beginning of a number.)
1397 The following variables work differently
1401 ARGC \h'|2.5i'$#ARGV
1403 FILENAME\h'|2.5i'$ARGV
1404 FNR \h'|2.5i'$. \- something
1405 FS \h'|2.5i'(whatever you like)
1406 NF \h'|2.5i'$#Fld, or some such
1411 RLENGTH \h'|2.5i'length($&)
1413 RSTART \h'|2.5i'length($\`)
1418 When in doubt, run the
1420 construct through a2p and see what it gives you.
1422 Cerebral C programmers should take note of the following:
1424 Curly brackets are required on ifs and whiles.
1426 You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
1437 There's no switch statement.
1439 Variables begin with $ or @ in
1442 Printf does not implement *.
1444 Comments begin with #, not /*.
1446 You can't take the address of anything.
1448 ARGV must be capitalized.
1450 The \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
1452 Signal handlers deal with signal names, not numbers.
1454 You can't subscript array values, only arrays (no $x = (1,2,3)[2];).
1458 programmers should take note of the following:
1460 Backreferences in substitutions use $ rather than \e.
1462 The pattern matching metacharacters (, ), and | do not have backslashes in front.
1464 The range operator is .\|. rather than comma.
1466 Sharp shell programmers should take note of the following:
1468 The backtick operator does variable interpretation without regard to the
1469 presence of single quotes in the command.
1471 The backtick operator does no translation of the return value, unlike csh.
1473 Shells (especially csh) do several levels of substitution on each command line.
1475 does substitution only in certain constructs such as double quotes,
1476 backticks, angle brackets and search patterns.
1478 Shells interpret scripts a little bit at a time.
1480 compiles the whole program before executing it.
1482 The arguments are available via @ARGV, not $1, $2, etc.
1484 The environment is not automatically made available as variables.
1488 is at the mercy of your machine's definitions of various operations
1489 such as type casting, atof() and sprintf().
1491 If your stdio requires an seek or eof between reads and writes on a particular
1495 While none of the built-in data types have any arbitrary size limits (apart
1496 from memory size), there are still a few arbitrary limits:
1497 a given identifier may not be longer than 255 characters;
1498 sprintf is limited on many machines to 128 characters per field (unless the format
1499 specifier is exactly %s);
1500 and no component of your PATH may be longer than 255 if you use \-S.
1503 actually stands for Pathologically Eclectic Rubbish Lister, but don't tell