1 ''' Beginning of part 4
2 ''' $Header: perl_man.4,v 3.0.1.13 90/11/10 01:51:00 lwall Locked $
4 ''' $Log: perl.man.4,v $
5 ''' Revision 3.0.1.13 90/11/10 01:51:00 lwall
6 ''' patch38: random cleanup
8 ''' Revision 3.0.1.12 90/10/20 02:15:43 lwall
9 ''' patch37: patch37: fixed various typos in man page
11 ''' Revision 3.0.1.11 90/10/16 10:04:28 lwall
12 ''' patch29: added @###.## fields to format
14 ''' Revision 3.0.1.10 90/08/09 04:47:35 lwall
15 ''' patch19: added require operator
16 ''' patch19: added numeric interpretation of $]
18 ''' Revision 3.0.1.9 90/08/03 11:15:58 lwall
19 ''' patch19: Intermediate diffs for Randal
21 ''' Revision 3.0.1.8 90/03/27 16:19:31 lwall
22 ''' patch16: MSDOS support
24 ''' Revision 3.0.1.7 90/03/14 12:29:50 lwall
25 ''' patch15: man page falsely states that you can't subscript array values
27 ''' Revision 3.0.1.6 90/03/12 16:54:04 lwall
28 ''' patch13: improved documentation of *name
30 ''' Revision 3.0.1.5 90/02/28 18:01:52 lwall
31 ''' patch9: $0 is now always the command name
33 ''' Revision 3.0.1.4 89/12/21 20:12:39 lwall
34 ''' patch7: documented that package'filehandle works as well as $package'variable
35 ''' patch7: documented which identifiers are always in package main
37 ''' Revision 3.0.1.3 89/11/17 15:32:25 lwall
38 ''' patch5: fixed some manual typos and indent problems
39 ''' patch5: clarified difference between $! and $@
41 ''' Revision 3.0.1.2 89/11/11 04:46:40 lwall
42 ''' patch2: made some line breaks depend on troff vs. nroff
43 ''' patch2: clarified operation of ^ and $ when $* is false
45 ''' Revision 3.0.1.1 89/10/26 23:18:43 lwall
46 ''' patch1: documented the desirability of unnecessary parentheses
48 ''' Revision 3.0 89/10/18 15:21:55 lwall
53 operators have the following associativity and precedence:
56 nonassoc\h'|1i'print printf exec system sort reverse
57 \h'1.5i'chmod chown kill unlink utime die return
59 right\h'|1i'= += \-= *= etc.
66 nonassoc\h'|1i'== != <=> eq ne cmp
67 nonassoc\h'|1i'< > <= >= lt gt le ge
68 nonassoc\h'|1i'chdir exit eval reset sleep rand umask
69 nonassoc\h'|1i'\-r \-w \-x etc.
74 right\h'|1i'! ~ and unary minus
76 nonassoc\h'|1i'++ \-\|\-
77 left\h'|1i'\*(L'(\*(R'
80 As mentioned earlier, if any list operator (print, etc.) or
81 any unary operator (chdir, etc.)
82 is followed by a left parenthesis as the next token on the same line,
83 the operator and arguments within parentheses are taken to
84 be of highest precedence, just like a normal function call.
88 chdir $foo || die;\h'|3i'# (chdir $foo) || die
89 chdir($foo) || die;\h'|3i'# (chdir $foo) || die
90 chdir ($foo) || die;\h'|3i'# (chdir $foo) || die
91 chdir +($foo) || die;\h'|3i'# (chdir $foo) || die
93 but, because * is higher precedence than ||:
95 chdir $foo * 20;\h'|3i'# chdir ($foo * 20)
96 chdir($foo) * 20;\h'|3i'# (chdir $foo) * 20
97 chdir ($foo) * 20;\h'|3i'# (chdir $foo) * 20
98 chdir +($foo) * 20;\h'|3i'# chdir ($foo * 20)
100 rand 10 * 20;\h'|3i'# rand (10 * 20)
101 rand(10) * 20;\h'|3i'# (rand 10) * 20
102 rand (10) * 20;\h'|3i'# (rand 10) * 20
103 rand +(10) * 20;\h'|3i'# rand (10 * 20)
106 In the absence of parentheses,
107 the precedence of list operators such as print, sort or chmod is
108 either very high or very low depending on whether you look at the left
109 side of operator or the right side of it.
113 @ary = (1, 3, sort 4, 2);
114 print @ary; # prints 1324
117 the commas on the right of the sort are evaluated before the sort, but
118 the commas on the left are evaluated after.
119 In other words, list operators tend to gobble up all the arguments that
120 follow them, and then act like a simple term with regard to the preceding
122 Note that you have to be careful with parens:
126 # These evaluate exit before doing the print:
127 print($foo, exit); # Obviously not what you want.
128 print $foo, exit; # Nor is this.
131 # These do the print before evaluating exit:
132 (print $foo), exit; # This is what you want.
133 print($foo), exit; # Or this.
134 print ($foo), exit; # Or even this.
138 print ($foo & 255) + 1, "\en";
141 probably doesn't do what you expect at first glance.
143 A subroutine may be declared as follows:
150 Any arguments passed to the routine come in as array @_,
151 that is ($_[0], $_[1], .\|.\|.).
152 The array @_ is a local array, but its values are references to the
153 actual scalar parameters.
154 The return value of the subroutine is the value of the last expression
155 evaluated, and can be either an array value or a scalar value.
156 Alternately, a return statement may be used to specify the returned value and
158 To create local variables see the
162 A subroutine is called using the
164 operator or the & operator.
171 local($max) = pop(@_);
173 $max = $foo \|if \|$max < $foo;
179 $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
184 # get a line, combining continuation lines
185 # that start with whitespace
187 $thisline = $lookahead;
188 line: while ($lookahead = <STDIN>) {
189 if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
190 $thisline \|.= \|$lookahead;
199 $lookahead = <STDIN>; # get first line
200 while ($_ = do get_line(\|)) {
207 Use array assignment to a local list to name your formal arguments:
210 local($key, $value) = @_;
211 $foo{$key} = $value unless $foo{$key};
215 This also has the effect of turning call-by-reference into call-by-value,
216 since the assignment copies the values.
218 Subroutines may be called recursively.
219 If a subroutine is called using the & form, the argument list is optional.
220 If omitted, no @_ array is set up for the subroutine; the @_ array at the
221 time of the call is visible to subroutine instead.
224 do foo(1,2,3); # pass three arguments
225 &foo(1,2,3); # the same
227 do foo(); # pass a null list
229 &foo; # pass no arguments\*(--more efficient
232 .Sh "Passing By Reference"
233 Sometimes you don't want to pass the value of an array to a subroutine but
234 rather the name of it, so that the subroutine can modify the global copy
235 of it rather than working with a local copy.
236 In perl you can refer to all the objects of a particular name by prefixing
237 the name with a star: *foo.
238 When evaluated, it produces a scalar value that represents all the objects
239 of that name, including any filehandle, format or subroutine.
240 When assigned to within a local() operation, it causes the name mentioned
241 to refer to whatever * value was assigned to it.
246 local(*someary) = @_;
247 foreach $elem (@someary) {
255 Assignment to *name is currently recommended only inside a local().
256 You can actually assign to *name anywhere, but the previous referent of
257 *name may be stranded forever.
258 This may or may not bother you.
260 Note that scalars are already passed by reference, so you can modify scalar
261 arguments without using this mechanism by referring explicitly to the $_[nnn]
263 You can modify all the elements of an array by passing all the elements
264 as scalars, but you have to use the * mechanism to push, pop or change the
266 The * mechanism will probably be more efficient in any case.
268 Since a *name value contains unprintable binary data, if it is used as
269 an argument in a print, or as a %s argument in a printf or sprintf, it
270 then has the value '*name', just so it prints out pretty.
272 Even if you don't want to modify an array, this mechanism is useful for
273 passing multiple arrays in a single LIST, since normally the LIST mechanism
274 will merge all the array values so that you can't extract out the
276 .Sh "Regular Expressions"
277 The patterns used in pattern matching are regular expressions such as
278 those supplied in the Version 8 regexp routines.
279 (In fact, the routines are derived from Henry Spencer's freely redistributable
280 reimplementation of the V8 routines.)
281 In addition, \ew matches an alphanumeric character (including \*(L"_\*(R") and \eW a nonalphanumeric.
282 Word boundaries may be matched by \eb, and non-boundaries by \eB.
283 A whitespace character is matched by \es, non-whitespace by \eS.
284 A numeric character is matched by \ed, non-numeric by \eD.
285 You may use \ew, \es and \ed within character classes.
286 Also, \en, \er, \ef, \et and \eNNN have their normal interpretations.
287 Within character classes \eb represents backspace rather than a word boundary.
288 Alternatives may be separated by |.
289 The bracketing construct \|(\ .\|.\|.\ \|) may also be used, in which case \e<digit>
290 matches the digit'th substring, where digit can range from 1 to 9.
291 (Outside of the pattern, always use $ instead of \e in front of the digit.
292 The scope of $<digit> (and $\`, $& and $\')
293 extends to the end of the enclosing BLOCK or eval string, or to
294 the next pattern match with subexpressions.
295 The \e<digit> notation sometimes works outside the current pattern, but should
297 $+ returns whatever the last bracket match matched.
298 $& returns the entire matched string.
299 ($0 used to return the same thing, but not any more.)
300 $\` returns everything before the matched string.
301 $\' returns everything after the matched string.
305 s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/; # swap first two words
308 if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
315 By default, the ^ character is only guaranteed to match at the beginning
317 the $ character only at the end (or before the newline at the end)
320 does certain optimizations with the assumption that the string contains
322 The behavior of ^ and $ on embedded newlines will be inconsistent.
323 You may, however, wish to treat a string as a multi-line buffer, such that
324 the ^ will match after any newline within the string, and $ will match
326 At the cost of a little more overhead, you can do this by setting the variable
328 Setting it back to 0 makes
330 revert to its old behavior.
332 To facilitate multi-line substitutions, the . character never matches a newline
334 In particular, the following leaves a newline on the $_ string:
338 s/.*(some_string).*/$1/;
340 If the newline is unwanted, try one of
342 s/.*(some_string).*\en/$1/;
343 s/.*(some_string)[^\e000]*/$1/;
344 s/.*(some_string)(.|\en)*/$1/;
345 chop; s/.*(some_string).*/$1/;
346 /(some_string)/ && ($_ = $1);
349 Any item of a regular expression may be followed with digits in curly brackets
350 of the form {n,m}, where n gives the minimum number of times to match the item
351 and m gives the maximum.
352 The form {n} is equivalent to {n,n} and matches exactly n times.
353 The form {n,} matches n or more times.
354 (If a curly bracket occurs in any other context, it is treated as a regular
356 The * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
358 There is no limit to the size of n or m, but large numbers will chew up
361 You will note that all backslashed metacharacters in
364 such as \eb, \ew, \en.
365 Unlike some other regular expression languages, there are no backslashed
366 symbols that aren't alphanumeric.
367 So anything that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} is always
368 interpreted as a literal character, not a metacharacter.
369 This makes it simple to quote a string that you want to use for a pattern
370 but that you are afraid might contain metacharacters.
371 Simply quote all the non-alphanumeric characters:
374 $pattern =~ s/(\eW)/\e\e$1/g;
378 Output record formats for use with the
380 operator may declared as follows:
389 If name is omitted, format \*(L"STDOUT\*(R" is defined.
390 FORMLIST consists of a sequence of lines, each of which may be of one of three
395 A \*(L"picture\*(R" line giving the format for one output line.
397 An argument line supplying values to plug into a picture line.
399 Picture lines are printed exactly as they look, except for certain fields
400 that substitute values into the line.
401 Each picture field starts with either @ or ^.
402 The @ field (not to be confused with the array marker @) is the normal
403 case; ^ fields are used
404 to do rudimentary multi-line text block filling.
405 The length of the field is supplied by padding out the field
406 with multiple <, >, or | characters to specify, respectively, left justification,
407 right justification, or centering.
408 As an alternate form of right justification,
409 you may also use # characters (with an optional .) to specify a numeric field.
410 If any of the values supplied for these fields contains a newline, only
411 the text up to the newline is printed.
412 The special field @* can be used for printing multi-line values.
413 It should appear by itself on a line.
415 The values are specified on the following line, in the same order as
417 The values should be separated by commas.
419 Picture fields that begin with ^ rather than @ are treated specially.
420 The value supplied must be a scalar variable name which contains a text
423 puts as much text as it can into the field, and then chops off the front
424 of the string so that the next time the variable is referenced,
425 more of the text can be printed.
426 Normally you would use a sequence of fields in a vertical stack to print
428 If you like, you can end the final field with .\|.\|., which will appear in the
429 output if the text was too long to appear in its entirety.
430 You can change which characters are legal to break on by changing the
431 variable $: to a list of the desired characters.
433 Since use of ^ fields can produce variable length records if the text to be
434 formatted is short, you can suppress blank lines by putting the tilde (~)
435 character anywhere in the line.
436 (Normally you should put it in the front if possible, for visibility.)
437 The tilde will be translated to a space upon output.
438 If you put a second tilde contiguous to the first, the line will be repeated
439 until all the fields on the line are exhausted.
440 (If you use a field of the @ variety, the expression you supply had better
441 not give the same value every time forever!)
450 # a report on the /etc/passwd file
453 Name Login Office Uid Gid Home
454 ------------------------------------------------------------------
457 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
458 $name, $login, $office,$uid,$gid, $home
462 # a report from a bug report form
465 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
467 ------------------------------------------------------------------
470 Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
472 Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
473 \& $index, $description
474 Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
475 \& $priority, $date, $description
476 From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
477 \& $from, $description
478 Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
479 \& $programmer, $description
480 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
482 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
484 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
486 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
488 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<...
496 It is possible to intermix prints with writes on the same output channel,
497 but you'll have to handle $\- (lines left on the page) yourself.
499 If you are printing lots of fields that are usually blank, you should consider
500 using the reset operator between records.
501 Not only is it more efficient, but it can prevent the bug of adding another
502 field and forgetting to zero it.
503 .Sh "Interprocess Communication"
504 The IPC facilities of perl are built on the Berkeley socket mechanism.
505 If you don't have sockets, you can ignore this section.
506 The calls have the same names as the corresponding system calls,
507 but the arguments tend to differ, for two reasons.
508 First, perl file handles work differently than C file descriptors.
509 Second, perl already knows the length of its strings, so you don't need
510 to pass that information.
511 Here is a sample client (untested):
514 ($them,$port) = @ARGV;
515 $port = 2345 unless $port;
516 $them = 'localhost' unless $them;
518 $SIG{'INT'} = 'dokill';
519 sub dokill { kill 9,$child if $child; }
521 require 'sys/socket.ph';
523 $sockaddr = 'S n a4 x8';
524 chop($hostname = `hostname`);
526 ($name, $aliases, $proto) = getprotobyname('tcp');
527 ($name, $aliases, $port) = getservbyname($port, 'tcp')
528 unless $port =~ /^\ed+$/;
530 ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
533 ($name, $aliases, $type, $len, $thisaddr) =
534 gethostbyname($hostname);
536 ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
538 $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
539 $that = pack($sockaddr, &AF_INET, $port, $thataddr);
541 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
542 bind(S, $this) || die "bind: $!";
543 connect(S, $that) || die "connect: $!";
545 select(S); $| = 1; select(stdout);
565 $port = 2345 unless $port;
567 require 'sys/socket.ph';
569 $sockaddr = 'S n a4 x8';
571 ($name, $aliases, $proto) = getprotobyname('tcp');
572 ($name, $aliases, $port) = getservbyname($port, 'tcp')
573 unless $port =~ /^\ed+$/;
575 $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
577 select(NS); $| = 1; select(stdout);
579 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
580 bind(S, $this) || die "bind: $!";
581 listen(S, 5) || die "connect: $!";
583 select(S); $| = 1; select(stdout);
586 print "Listening again\en";
587 ($addr = accept(NS,S)) || die $!;
588 print "accept ok\en";
590 ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
591 @inetaddr = unpack('C4',$inetaddr);
592 print "$af $port @inetaddr\en";
601 .Sh "Predefined Names"
602 The following names have special meaning to
604 I could have used alphabetic symbols for some of these, but I didn't want
605 to take the chance that someone would say reset \*(L"a\-zA\-Z\*(R" and wipe them all
607 You'll just have to suffer along with these silly symbols.
608 Most of them have reasonable mnemonics, or analogues in one of the shells.
610 The default input and pattern-searching space.
611 The following pairs are equivalent:
615 while (<>) {\|.\|.\|. # only equivalent in while!
616 while ($_ = <>) {\|.\|.\|.
620 $_ \|=~ \|/\|^Subject:/
631 (Mnemonic: underline is understood in certain operations.)
633 The current input line number of the last filehandle that was read.
635 Remember that only an explicit close on the filehandle resets the line number.
636 Since <> never does an explicit close, line numbers increase across ARGV files
637 (but see examples under eof).
638 (Mnemonic: many programs use . to mean the current line number.)
640 The input record separator, newline by default.
643 RS variable, including treating blank lines as delimiters
644 if set to the null string.
645 If set to a value longer than one character, only the first character is used.
646 (Mnemonic: / is used to delimit line boundaries when quoting poetry.)
648 The output field separator for the print operator.
649 Ordinarily the print operator simply prints out the comma separated fields
651 In order to get behavior more like
653 set this variable as you would set
655 OFS variable to specify what is printed between fields.
656 (Mnemonic: what is printed when there is a , in your print statement.)
658 This is like $, except that it applies to array values interpolated into
659 a double-quoted string (or similar interpreted string).
661 (Mnemonic: obvious, I think.)
663 The output record separator for the print operator.
664 Ordinarily the print operator simply prints out the comma separated fields
665 you specify, with no trailing newline or record separator assumed.
666 In order to get behavior more like
668 set this variable as you would set
670 ORS variable to specify what is printed at the end of the print.
671 (Mnemonic: you set $\e instead of adding \en at the end of the print.
672 Also, it's just like /, but it's what you get \*(L"back\*(R" from
675 The output format for printed numbers.
676 This variable is a half-hearted attempt to emulate
679 There are times, however, when
683 have differing notions of what
685 Also, the initial value is %.20g rather than %.6g, so you need to set $#
689 (Mnemonic: # is the number sign.)
691 The current page number of the currently selected output channel.
692 (Mnemonic: % is page number in nroff.)
694 The current page length (printable lines) of the currently selected output
697 (Mnemonic: = has horizontal lines.)
699 The number of lines left on the page of the currently selected output channel.
700 (Mnemonic: lines_on_page \- lines_printed.)
702 The name of the current report format for the currently selected output
704 (Mnemonic: brother to $^.)
706 The name of the current top-of-page format for the currently selected output
708 (Mnemonic: points to top of page.)
710 If set to nonzero, forces a flush after every write or print on the currently
711 selected output channel.
715 will typically be line buffered if output is to the
716 terminal and block buffered otherwise.
717 Setting this variable is useful primarily when you are outputting to a pipe,
718 such as when you are running a
720 script under rsh and want to see the
721 output as it's happening.
722 (Mnemonic: when you want your pipes to be piping hot.)
724 The process number of the
727 (Mnemonic: same as shells.)
729 The status returned by the last pipe close, backtick (\`\`) command or
732 Note that this is the status word returned by the wait() system
733 call, so the exit value of the subprocess is actually ($? >> 8).
734 $? & 255 gives which signal, if any, the process died from, and whether
735 there was a core dump.
736 (Mnemonic: similar to sh and ksh.)
738 The string matched by the last pattern match (not counting any matches hidden
739 within a BLOCK or eval enclosed by the current BLOCK).
740 (Mnemonic: like & in some editors.)
742 The string preceding whatever was matched by the last pattern match
743 (not counting any matches hidden within a BLOCK or eval enclosed by the current
745 (Mnemonic: \` often precedes a quoted string.)
747 The string following whatever was matched by the last pattern match
748 (not counting any matches hidden within a BLOCK or eval enclosed by the current
750 (Mnemonic: \' often follows a quoted string.)
757 print "$\`:$&:$\'\en"; # prints abc:def:ghi
761 The last bracket matched by the last search pattern.
762 This is useful if you don't know which of a set of alternative patterns
767 /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
770 (Mnemonic: be positive and forward looking.)
772 Set to 1 to do multiline matching within a string, 0 to tell
774 that it can assume that strings contain a single line, for the purpose
775 of optimizing pattern matches.
776 Pattern matches on strings containing multiple newlines can produce confusing
777 results when $* is 0.
779 (Mnemonic: * matches multiple things.)
780 Note that this variable only influences the interpretation of ^ and $.
781 A literal newline can be searched for even when $* == 0.
783 Contains the name of the file containing the
785 script being executed.
786 (Mnemonic: same as sh and ksh.)
788 Contains the subpattern from the corresponding set of parentheses in the last
789 pattern matched, not counting patterns matched in nested blocks that have
791 (Mnemonic: like \edigit.)
793 The index of the first element in an array, and of the first character in
795 Default is 0, but you could set it to 1 to make
800 when subscripting and when evaluating the index() and substr() functions.
801 (Mnemonic: [ begins subscripts.)
803 The string printed out when you say \*(L"perl -v\*(R".
804 It can be used to determine at the beginning of a script whether the perl
805 interpreter executing the script is in the right range of versions.
806 If used in a numeric context, returns the version + patchlevel / 1000.
811 # see if getc is available
812 ($version,$patchlevel) =
813 $] =~ /(\ed+\e.\ed+).*\enPatch level: (\ed+)/;
814 print STDERR "(No filename completion available.)\en"
815 if $version * 1000 + $patchlevel < 2016;
817 or, used numerically,
819 warn "No checksumming!\en" if $] < 3.019;
822 (Mnemonic: Is this version of perl in the right bracket?)
824 The subscript separator for multi-dimensional array emulation.
825 If you refer to an associative array element as
831 $foo{join($;, $a, $b, $c)}
835 @foo{$a,$b,$c} # a slice\*(--note the @
839 ($foo{$a},$foo{$b},$foo{$c})
842 Default is "\e034", the same as SUBSEP in
844 Note that if your keys contain binary data there might not be any safe
846 (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
847 Yeah, I know, it's pretty lame, but $, is already taken for something more
850 If used in a numeric context, yields the current value of errno, with all the
852 (This means that you shouldn't depend on the value of $! to be anything
853 in particular unless you've gotten a specific error return indicating a
855 If used in a string context, yields the corresponding system error string.
856 You can assign to $! in order to set errno
857 if, for instance, you want $! to return the string for error n, or you want
858 to set the exit value for the die operator.
859 (Mnemonic: What just went bang?)
861 The perl syntax error message from the last eval command.
862 If null, the last eval parsed and executed correctly (although the operations
863 you invoked may have failed in the normal fashion).
864 (Mnemonic: Where was the syntax error \*(L"at\*(R"?)
866 The real uid of this process.
867 (Mnemonic: it's the uid you came FROM, if you're running setuid.)
869 The effective uid of this process.
874 $< = $>; # set real uid to the effective uid
875 ($<,$>) = ($>,$<); # swap real and effective uid
878 (Mnemonic: it's the uid you went TO, if you're running setuid.)
879 Note: $< and $> can only be swapped on machines supporting setreuid().
881 The real gid of this process.
882 If you are on a machine that supports membership in multiple groups
883 simultaneously, gives a space separated list of groups you are in.
884 The first number is the one returned by getgid(), and the subsequent ones
885 by getgroups(), one of which may be the same as the first number.
886 (Mnemonic: parentheses are used to GROUP things.
887 The real gid is the group you LEFT, if you're running setgid.)
889 The effective gid of this process.
890 If you are on a machine that supports membership in multiple groups
891 simultaneously, gives a space separated list of groups you are in.
892 The first number is the one returned by getegid(), and the subsequent ones
893 by getgroups(), one of which may be the same as the first number.
894 (Mnemonic: parentheses are used to GROUP things.
895 The effective gid is the group that's RIGHT for you, if you're running setgid.)
897 Note: $<, $>, $( and $) can only be set on machines that support the
898 corresponding set[re][ug]id() routine.
899 $( and $) can only be swapped on machines supporting setregid().
901 The current set of characters after which a string may be broken to
902 fill continuation fields (starting with ^) in a format.
903 Default is "\ \en-", to break on whitespace or hyphens.
904 (Mnemonic: a \*(L"colon\*(R" in poetry is a part of a line.)
906 contains the name of the current file when reading from <>.
908 The array ARGV contains the command line arguments intended for the script.
909 Note that $#ARGV is the generally number of arguments minus one, since
910 $ARGV[0] is the first argument, NOT the command name.
911 See $0 for the command name.
913 The array INC contains the list of places to look for
916 evaluated by the \*(L"do EXPR\*(R" command or the \*(L"require\*(R" command.
917 It initially consists of the arguments to any
919 command line switches, followed
922 library, probably \*(L"/usr/local/lib/perl\*(R",
923 followed by \*(L".\*(R", to represent the current directory.
925 The associative array INC contains entries for each filename that has
926 been included via \*(L"do\*(R" or \*(L"require\*(R".
927 The key is the filename you specified, and the value is the location of
928 the file actually found.
929 The \*(L"require\*(R" command uses this array to determine whether
930 a given file has already been included.
932 The associative array ENV contains your current environment.
933 Setting a value in ENV changes the environment for child processes.
935 The associative array SIG is used to set signal handlers for various signals.
940 sub handler { # 1st argument is signal name
942 print "Caught a SIG$sig\-\|\-shutting down\en";
947 $SIG{\'INT\'} = \'handler\';
948 $SIG{\'QUIT\'} = \'handler\';
950 $SIG{\'INT\'} = \'DEFAULT\'; # restore default action
951 $SIG{\'QUIT\'} = \'IGNORE\'; # ignore SIGQUIT
954 The SIG array only contains values for the signals actually set within
957 Perl provides a mechanism for alternate namespaces to protect packages from
958 stomping on each others variables.
959 By default, a perl script starts compiling into the package known as \*(L"main\*(R".
962 declaration, you can switch namespaces.
963 The scope of the package declaration is from the declaration itself to the end
964 of the enclosing block (the same scope as the local() operator).
965 Typically it would be the first declaration in a file to be included by
966 the \*(L"require\*(R" operator.
967 You can switch into a package in more than one place; it merely influences
968 which symbol table is used by the compiler for the rest of that block.
969 You can refer to variables and filehandles in other packages by prefixing
970 the identifier with the package name and a single quote.
971 If the package name is null, the \*(L"main\*(R" package as assumed.
973 Only identifiers starting with letters are stored in the packages symbol
975 All other symbols are kept in package \*(L"main\*(R".
976 In addition, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC
977 and SIG are forced to be in package \*(L"main\*(R", even when used for
978 other purposes than their built-in one.
979 Note also that, if you have a package called \*(L"m\*(R", \*(L"s\*(R"
980 or \*(L"y\*(R", the you can't use the qualified form of an identifier since it
981 will be interpreted instead as a pattern match, a substitution
984 Eval'ed strings are compiled in the package in which the eval was compiled
986 (Assignments to $SIG{}, however, assume the signal handler specified is in the
988 Qualify the signal handler name if you wish to have a signal handler in
990 For an example, examine perldb.pl in the perl library.
991 It initially switches to the DB package so that the debugger doesn't interfere
992 with variables in the script you are trying to debug.
993 At various points, however, it temporarily switches back to the main package
994 to evaluate various expressions in the context of the main package.
996 The symbol table for a package happens to be stored in the associative array
997 of that name prepended with an underscore.
998 The value in each entry of the associative array is
999 what you are referring to when you use the *name notation.
1000 In fact, the following have the same effect (in package main, anyway),
1001 though the first is more
1002 efficient because it does the symbol table lookups at compile time:
1007 local($_main{'foo'}) = $_main{'bar'};
1010 You can use this to print out all the variables in a package, for instance.
1011 Here is dumpvar.pl from the perl library:
1018 \& local(*stab) = eval("*_$package");
1019 \& while (($key,$val) = each(%stab)) {
1021 \& local(*entry) = $val;
1022 \& if (defined $entry) {
1023 \& print "\e$$key = '$entry'\en";
1026 \& if (defined @entry) {
1027 \& print "\e@$key = (\en";
1028 \& foreach $num ($[ .. $#entry) {
1029 \& print " $num\et'",$entry[$num],"'\en";
1034 \& if ($key ne "_$package" && defined %entry) {
1035 \& print "\e%$key = (\en";
1036 \& foreach $key (sort keys(%entry)) {
1037 \& print " $key\et'",$entry{$key},"'\en";
1046 Note that, even though the subroutine is compiled in package dumpvar, the
1047 name of the subroutine is qualified so that its name is inserted into package
1050 Each programmer will, of course, have his or her own preferences in regards
1051 to formatting, but there are some general guidelines that will make your
1052 programs easier to read.
1054 Just because you CAN do something a particular way doesn't mean that
1055 you SHOULD do it that way.
1057 is designed to give you several ways to do anything, so consider picking
1058 the most readable one.
1061 open(FOO,$foo) || die "Can't open $foo: $!";
1065 die "Can't open $foo: $!" unless open(FOO,$foo);
1067 because the second way hides the main point of the statement in a
1071 print "Starting analysis\en" if $verbose;
1075 $verbose && print "Starting analysis\en";
1077 since the main point isn't whether the user typed -v or not.
1079 Similarly, just because an operator lets you assume default arguments
1080 doesn't mean that you have to make use of the defaults.
1081 The defaults are there for lazy systems programmers writing one-shot
1083 If you want your program to be readable, consider supplying the argument.
1085 Along the same lines, just because you
1087 omit parentheses in many places doesn't mean that you ought to:
1090 return print reverse sort num values array;
1091 return print(reverse(sort num (values(%array))));
1094 When in doubt, parenthesize.
1095 At the very least it will let some poor schmuck bounce on the % key in vi.
1097 Even if you aren't in doubt, consider the mental welfare of the person who
1098 has to maintain the code after you, and who will probably put parens in
1101 Don't go through silly contortions to exit a loop at the top or the
1104 provides the "last" operator so you can exit in the middle.
1105 Just outdent it a little to make it more visible:
1119 Don't be afraid to use loop labels\*(--they're there to enhance readability as
1120 well as to allow multi-level loop breaks.
1123 For portability, when using features that may not be implemented on every
1124 machine, test the construct in an eval to see if it fails.
1125 If you know what version or patchlevel a particular feature was implemented,
1126 you can test $] to see if it will be there.
1128 Choose mnemonic identifiers.
1136 switch, your script will be run under a debugging monitor.
1137 It will halt before the first executable statement and ask you for a
1140 Prints out a help message.
1145 Executes until it reaches the beginning of another statement.
1148 Executes over subroutine calls, until it reaches the beginning of the
1152 Executes statements until it has finished the current subroutine.
1155 Executes until the next breakpoint is reached.
1157 Continue to the specified line.
1158 Inserts a one-time-only breakpoint at the specified line.
1161 .Ip "l min+incr" 12 4
1162 List incr+1 lines starting at min.
1163 If min is omitted, starts where last listing left off.
1164 If incr is omitted, previous value of incr is used.
1165 .Ip "l min-max" 12 4
1166 List lines in the indicated range.
1168 List just the indicated line.
1172 List previous window.
1174 List window around line.
1175 .Ip "l subname" 12 4
1177 If it's a long subroutine it just lists the beginning.
1178 Use \*(L"l\*(R" to list more.
1179 .Ip "/pattern/" 12 4
1180 Regular expression search forward for pattern; the final / is optional.
1181 .Ip "?pattern?" 12 4
1182 Regular expression search backward for pattern; the final ? is optional.
1184 List lines that have breakpoints or actions.
1186 Lists the names of all subroutines.
1188 Toggle trace mode on or off.
1189 .Ip "b line condition" 12 4
1191 If line is omitted, sets a breakpoint on the
1192 line that is about to be executed.
1193 If a condition is specified, it is evaluated each time the statement is
1194 reached and a breakpoint is taken only if the condition is true.
1195 Breakpoints may only be set on lines that begin an executable statement.
1196 .Ip "b subname condition" 12 4
1197 Set breakpoint at first executable line of subroutine.
1200 If line is omitted, deletes the breakpoint on the
1201 line that is about to be executed.
1203 Delete all breakpoints.
1204 .Ip "a line command" 12 4
1205 Set an action for line.
1206 A multi-line command may be entered by backslashing the newlines.
1208 Delete all line actions.
1209 .Ip "< command" 12 4
1210 Set an action to happen before every debugger prompt.
1211 A multi-line command may be entered by backslashing the newlines.
1212 .Ip "> command" 12 4
1213 Set an action to happen after the prompt when you've just given a command
1214 to return to executing the script.
1215 A multi-line command may be entered by backslashing the newlines.
1216 .Ip "V package" 12 4
1217 List all variables in package.
1218 Default is main package.
1220 Redo a debugging command.
1221 If number is omitted, redoes the previous command.
1222 .Ip "! -number" 12 4
1223 Redo the command that was that many commands ago.
1224 .Ip "H -number" 12 4
1225 Display last n commands.
1226 Only commands longer than one character are listed.
1227 If number is omitted, lists them all.
1231 Execute command as a perl statement.
1232 A missing semicolon will be supplied.
1234 Same as \*(L"print DB'OUT expr\*(R".
1235 The DB'OUT filehandle is opened to /dev/tty, regardless of where STDOUT
1236 may be redirected to.
1238 If you want to modify the debugger, copy perldb.pl from the perl library
1239 to your current directory and modify it as necessary.
1240 (You'll also have to put -I. on your command line.)
1241 You can do some customization by setting up a .perldb file which contains
1242 initialization code.
1243 For instance, you could make aliases like these:
1246 $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
1247 $DB'alias{'stop'} = 's/^stop (at|in)/b/';
1249 's/^\e./p "\e$DB\e'sub(\e$DB\e'line):\et",\e$DB\e'line[\e$DB\e'line]/';
1252 .Sh "Setuid Scripts"
1254 is designed to make it easy to write secure setuid and setgid scripts.
1255 Unlike shells, which are based on multiple substitution passes on each line
1258 uses a more conventional evaluation scheme with fewer hidden \*(L"gotchas\*(R".
1259 Additionally, since the language has more built-in functionality, it
1260 has to rely less upon external (and possibly untrustworthy) programs to
1261 accomplish its purposes.
1263 In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
1264 insecure, but this kernel feature can be disabled.
1267 can emulate the setuid and setgid mechanism when it notices the otherwise
1268 useless setuid/gid bits on perl scripts.
1269 If the kernel feature isn't disabled,
1271 will complain loudly that your setuid script is insecure.
1272 You'll need to either disable the kernel setuid script feature, or put
1273 a C wrapper around the script.
1275 When perl is executing a setuid script, it takes special precautions to
1276 prevent you from falling into any obvious traps.
1277 (In some ways, a perl script is more secure than the corresponding
1279 Any command line argument, environment variable, or input is marked as
1280 \*(L"tainted\*(R", and may not be used, directly or indirectly, in any
1281 command that invokes a subshell, or in any command that modifies files,
1282 directories or processes.
1283 Any variable that is set within an expression that has previously referenced
1284 a tainted value also becomes tainted (even if it is logically impossible
1285 for the tainted value to influence the variable).
1290 $foo = shift; # $foo is tainted
1291 $bar = $foo,\'bar\'; # $bar is also tainted
1292 $xxx = <>; # Tainted
1293 $path = $ENV{\'PATH\'}; # Tainted, but see below
1294 $abc = \'abc\'; # Not tainted
1297 system "echo $foo"; # Insecure
1298 system "/bin/echo", $foo; # Secure (doesn't use sh)
1299 system "echo $bar"; # Insecure
1300 system "echo $abc"; # Insecure until PATH set
1303 $ENV{\'PATH\'} = \'/bin:/usr/bin\';
1304 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1306 $path = $ENV{\'PATH\'}; # Not tainted
1307 system "echo $abc"; # Is secure now!
1310 open(FOO,"$foo"); # OK
1311 open(FOO,">$foo"); # Not OK
1313 open(FOO,"echo $foo|"); # Not OK, but...
1314 open(FOO,"-|") || exec \'echo\', $foo; # OK
1316 $zzz = `echo $foo`; # Insecure, zzz tainted
1318 unlink $abc,$foo; # Insecure
1319 umask $foo; # Insecure
1322 exec "echo $foo"; # Insecure
1323 exec "echo", $foo; # Secure (doesn't use sh)
1324 exec "sh", \'-c\', $foo; # Considered secure, alas
1327 The taintedness is associated with each scalar value, so some elements
1328 of an array can be tainted, and others not.
1330 If you try to do something insecure, you will get a fatal error saying
1331 something like \*(L"Insecure dependency\*(R" or \*(L"Insecure PATH\*(R".
1332 Note that you can still write an insecure system call or exec,
1333 but only by explicitly doing something like the last example above.
1334 You can also bypass the tainting mechanism by referencing
1337 presumes that if you reference a substring using $1, $2, etc, you knew
1338 what you were doing when you wrote the pattern:
1341 $ARGV[0] =~ /^\-P(\ew+)$/;
1342 $printer = $1; # Not tainted
1345 This is fairly secure since \ew+ doesn't match shell metacharacters.
1346 Use of .+ would have been insecure, but
1348 doesn't check for that, so you must be careful with your patterns.
1349 This is the ONLY mechanism for untainting user supplied filenames if you
1350 want to do file operations on them (unless you make $> equal to $<).
1352 It's also possible to get into trouble with other operations that don't care
1353 whether they use tainted values.
1354 Make judicious use of the file tests in dealing with any user-supplied
1356 When possible, do opens and such after setting $> = $<.
1358 doesn't prevent you from opening tainted filenames for reading, so be
1359 careful what you print out.
1360 The tainting mechanism is intended to prevent stupid mistakes, not to remove
1361 the need for thought.
1364 uses PATH in executing subprocesses, and in finding the script if \-S
1366 HOME or LOGDIR are used if chdir has no argument.
1370 uses no environment variables, except to make them available
1371 to the script being executed, and to child processes.
1372 However, scripts running setuid would do well to execute the following lines
1373 before doing anything else, just to keep people honest:
1377 $ENV{\'PATH\'} = \'/bin:/usr/bin\'; # or whatever you need
1378 $ENV{\'SHELL\'} = \'/bin/sh\' if $ENV{\'SHELL\'} ne \'\';
1379 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1383 Larry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
1385 MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk>
1387 /tmp/perl\-eXXXXXX temporary file for
1391 a2p awk to perl translator
1393 s2p sed to perl translator
1395 Compilation errors will tell you the line number of the error, with an
1396 indication of the next token or token type that was to be examined.
1397 (In the case of a script passed to
1403 is counted as one line.)
1405 Setuid scripts have additional constraints that can produce error messages
1406 such as \*(L"Insecure dependency\*(R".
1407 See the section on setuid scripts.
1411 users should take special note of the following:
1413 Semicolons are required after all simple statements in
1416 is not a statement delimiter.
1418 Curly brackets are required on ifs and whiles.
1420 Variables begin with $ or @ in
1423 Arrays index from 0 unless you set $[.
1424 Likewise string positions in substr() and index().
1426 You have to decide whether your array has numeric or string indices.
1428 Associative array values do not spring into existence upon mere reference.
1430 You have to decide whether you want to use string or numeric comparisons.
1432 Reading an input line does not split it for you. You get to split it yourself
1436 operator has different arguments.
1438 The current input line is normally in $_, not $0.
1439 It generally does not have the newline stripped.
1440 ($0 is the name of the program executed.)
1442 $<digit> does not refer to fields\*(--it refers to substrings matched by the last
1447 statement does not add field and record separators unless you set
1450 You must open your files before you print to them.
1452 The range operator is \*(L".\|.\*(R", not comma.
1453 (The comma operator works as in C.)
1455 The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
1456 (\*(L"~\*(R" is the one's complement operator, as in C.)
1458 The exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
1459 (\*(L"^\*(R" is the XOR operator, as in C.)
1461 The concatenation operator is \*(L".\*(R", not the null string.
1462 (Using the null string would render \*(L"/pat/ /pat/\*(R" unparsable,
1463 since the third slash would be interpreted as a division operator\*(--the
1464 tokener is in fact slightly context sensitive for operators like /, ?, and <.
1465 And in fact, . itself can be the beginning of a number.)
1473 The following variables work differently
1477 ARGC \h'|2.5i'$#ARGV
1479 FILENAME\h'|2.5i'$ARGV
1480 FNR \h'|2.5i'$. \- something
1481 FS \h'|2.5i'(whatever you like)
1482 NF \h'|2.5i'$#Fld, or some such
1487 RLENGTH \h'|2.5i'length($&)
1489 RSTART \h'|2.5i'length($\`)
1494 When in doubt, run the
1496 construct through a2p and see what it gives you.
1498 Cerebral C programmers should take note of the following:
1500 Curly brackets are required on ifs and whiles.
1502 You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
1513 There's no switch statement.
1515 Variables begin with $ or @ in
1518 Printf does not implement *.
1520 Comments begin with #, not /*.
1522 You can't take the address of anything.
1524 ARGV must be capitalized.
1526 The \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
1528 Signal handlers deal with signal names, not numbers.
1532 programmers should take note of the following:
1534 Backreferences in substitutions use $ rather than \e.
1536 The pattern matching metacharacters (, ), and | do not have backslashes in front.
1538 The range operator is .\|. rather than comma.
1540 Sharp shell programmers should take note of the following:
1542 The backtick operator does variable interpretation without regard to the
1543 presence of single quotes in the command.
1545 The backtick operator does no translation of the return value, unlike csh.
1547 Shells (especially csh) do several levels of substitution on each command line.
1549 does substitution only in certain constructs such as double quotes,
1550 backticks, angle brackets and search patterns.
1552 Shells interpret scripts a little bit at a time.
1554 compiles the whole program before executing it.
1556 The arguments are available via @ARGV, not $1, $2, etc.
1558 The environment is not automatically made available as variables.
1562 is at the mercy of your machine's definitions of various operations
1563 such as type casting, atof() and sprintf().
1565 If your stdio requires an seek or eof between reads and writes on a particular
1569 While none of the built-in data types have any arbitrary size limits (apart
1570 from memory size), there are still a few arbitrary limits:
1571 a given identifier may not be longer than 255 characters;
1572 sprintf is limited on many machines to 128 characters per field (unless the format
1573 specifier is exactly %s);
1574 and no component of your PATH may be longer than 255 if you use \-S.
1577 actually stands for Pathologically Eclectic Rubbish Lister, but don't tell