1 ''' Beginning of part 4
2 ''' $Header: perl.man.4,v 3.0.1.3 89/11/17 15:32:25 lwall Locked $
4 ''' $Log: perl.man.4,v $
5 ''' Revision 3.0.1.3 89/11/17 15:32:25 lwall
6 ''' patch5: fixed some manual typos and indent problems
7 ''' patch5: clarified difference between $! and $@
9 ''' Revision 3.0.1.2 89/11/11 04:46:40 lwall
10 ''' patch2: made some line breaks depend on troff vs. nroff
11 ''' patch2: clarified operation of ^ and $ when $* is false
13 ''' Revision 3.0.1.1 89/10/26 23:18:43 lwall
14 ''' patch1: documented the desirability of unnecessary parentheses
16 ''' Revision 3.0 89/10/18 15:21:55 lwall
21 operators have the following associativity and precedence:
24 nonassoc\h'|1i'print printf exec system sort reverse
25 \h'1.5i'chmod chown kill unlink utime die return
27 right\h'|1i'= += \-= *= etc.
34 nonassoc\h'|1i'== != eq ne
35 nonassoc\h'|1i'< > <= >= lt gt le ge
36 nonassoc\h'|1i'chdir exit eval reset sleep rand umask
37 nonassoc\h'|1i'\-r \-w \-x etc.
42 right\h'|1i'! ~ and unary minus
44 nonassoc\h'|1i'++ \-\|\-
45 left\h'|1i'\*(L'(\*(R'
48 As mentioned earlier, if any list operator (print, etc.) or
49 any unary operator (chdir, etc.)
50 is followed by a left parenthesis as the next token on the same line,
51 the operator and arguments within parentheses are taken to
52 be of highest precedence, just like a normal function call.
56 chdir $foo || die;\h'|3i'# (chdir $foo) || die
57 chdir($foo) || die;\h'|3i'# (chdir $foo) || die
58 chdir ($foo) || die;\h'|3i'# (chdir $foo) || die
59 chdir +($foo) || die;\h'|3i'# (chdir $foo) || die
61 but, because * is higher precedence than ||:
63 chdir $foo * 20;\h'|3i'# chdir ($foo * 20)
64 chdir($foo) * 20;\h'|3i'# (chdir $foo) * 20
65 chdir ($foo) * 20;\h'|3i'# (chdir $foo) * 20
66 chdir +($foo) * 20;\h'|3i'# chdir ($foo * 20)
68 rand 10 * 20;\h'|3i'# rand (10 * 20)
69 rand(10) * 20;\h'|3i'# (rand 10) * 20
70 rand (10) * 20;\h'|3i'# (rand 10) * 20
71 rand +(10) * 20;\h'|3i'# rand (10 * 20)
74 In the absence of parentheses,
75 the precedence of list operators such as print, sort or chmod is
76 either very high or very low depending on whether you look at the left
77 side of operator or the right side of it.
81 @ary = (1, 3, sort 4, 2);
82 print @ary; # prints 1324
85 the commas on the right of the sort are evaluated before the sort, but
86 the commas on the left are evaluated after.
87 In other words, list operators tend to gobble up all the arguments that
88 follow them, and then act like a simple term with regard to the preceding
90 Note that you have to be careful with parens:
94 # These evaluate exit before doing the print:
95 print($foo, exit); # Obviously not what you want.
96 print $foo, exit; # Nor is this.
99 # These do the print before evaluating exit:
100 (print $foo), exit; # This is what you want.
101 print($foo), exit; # Or this.
102 print ($foo), exit; # Or even this.
106 print ($foo & 255) + 1, "\en";
109 probably doesn't do what you expect at first glance.
111 A subroutine may be declared as follows:
118 Any arguments passed to the routine come in as array @_,
119 that is ($_[0], $_[1], .\|.\|.).
120 The array @_ is a local array, but its values are references to the
121 actual scalar parameters.
122 The return value of the subroutine is the value of the last expression
123 evaluated, and can be either an array value or a scalar value.
124 Alternately, a return statement may be used to specify the returned value and
126 To create local variables see the
130 A subroutine is called using the
132 operator or the & operator.
139 local($max) = pop(@_);
141 $max = $foo \|if \|$max < $foo;
147 $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
152 # get a line, combining continuation lines
153 # that start with whitespace
155 $thisline = $lookahead;
156 line: while ($lookahead = <STDIN>) {
157 if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
158 $thisline \|.= \|$lookahead;
167 $lookahead = <STDIN>; # get first line
168 while ($_ = do get_line(\|)) {
175 Use array assignment to a local list to name your formal arguments:
178 local($key, $value) = @_;
179 $foo{$key} = $value unless $foo{$key};
183 This also has the effect of turning call-by-reference into call-by-value,
184 since the assignment copies the values.
186 Subroutines may be called recursively.
187 If a subroutine is called using the & form, the argument list is optional.
188 If omitted, no @_ array is set up for the subroutine; the @_ array at the
189 time of the call is visible to subroutine instead.
192 do foo(1,2,3); # pass three arguments
193 &foo(1,2,3); # the same
195 do foo(); # pass a null list
197 &foo; # pass no arguments--more efficient
200 .Sh "Passing By Reference"
201 Sometimes you don't want to pass the value of an array to a subroutine but
202 rather the name of it, so that the subroutine can modify the global copy
203 of it rather than working with a local copy.
204 In perl you can refer to all the objects of a particular name by prefixing
205 the name with a star: *foo.
206 When evaluated, it produces a scalar value that represents all the objects
208 When assigned to within a local() operation, it causes the name mentioned
209 to refer to whatever * value was assigned to it.
214 local(*someary) = @_;
215 foreach $elem (@someary) {
223 Assignment to *name is currently recommended only inside a local().
224 You can actually assign to *name anywhere, but the previous referent of
225 *name may be stranded forever.
226 This may or may not bother you.
228 Note that scalars are already passed by reference, so you can modify scalar
229 arguments without using this mechanism by referring explicitly to the $_[nnn]
231 You can modify all the elements of an array by passing all the elements
232 as scalars, but you have to use the * mechanism to push, pop or change the
234 The * mechanism will probably be more efficient in any case.
236 Since a *name value contains unprintable binary data, if it is used as
237 an argument in a print, or as a %s argument in a printf or sprintf, it
238 then has the value '*name', just so it prints out pretty.
239 .Sh "Regular Expressions"
240 The patterns used in pattern matching are regular expressions such as
241 those supplied in the Version 8 regexp routines.
242 (In fact, the routines are derived from Henry Spencer's freely redistributable
243 reimplementation of the V8 routines.)
244 In addition, \ew matches an alphanumeric character (including \*(L"_\*(R") and \eW a nonalphanumeric.
245 Word boundaries may be matched by \eb, and non-boundaries by \eB.
246 A whitespace character is matched by \es, non-whitespace by \eS.
247 A numeric character is matched by \ed, non-numeric by \eD.
248 You may use \ew, \es and \ed within character classes.
249 Also, \en, \er, \ef, \et and \eNNN have their normal interpretations.
250 Within character classes \eb represents backspace rather than a word boundary.
251 Alternatives may be separated by |.
252 The bracketing construct \|(\ .\|.\|.\ \|) may also be used, in which case \e<digit>
253 matches the digit'th substring, where digit can range from 1 to 9.
254 (Outside of the pattern, always use $ instead of \e in front of the digit.
255 The scope of $<digit> (and $\`, $& and $\')
256 extends to the end of the enclosing BLOCK or eval string, or to
257 the next pattern match with subexpressions.
258 The \e<digit> notation sometimes works outside the current pattern, but should
260 $+ returns whatever the last bracket match matched.
261 $& returns the entire matched string.
262 ($0 normally returns the same thing, but don't depend on it.)
263 $\` returns everything before the matched string.
264 $\' returns everything after the matched string.
268 s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/; # swap first two words
271 if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
278 By default, the ^ character is only guaranteed to match at the beginning
280 the $ character only at the end (or before the newline at the end)
283 does certain optimizations with the assumption that the string contains
285 The behavior of ^ and $ on embedded newlines will be inconsistent.
286 You may, however, wish to treat a string as a multi-line buffer, such that
287 the ^ will match after any newline within the string, and $ will match
289 At the cost of a little more overhead, you can do this by setting the variable
291 Setting it back to 0 makes
293 revert to its old behavior.
295 To facilitate multi-line substitutions, the . character never matches a newline
297 In particular, the following leaves a newline on the $_ string:
301 s/.*(some_string).*/$1/;
303 If the newline is unwanted, try one of
305 s/.*(some_string).*\en/$1/;
306 s/.*(some_string)[^\e000]*/$1/;
307 s/.*(some_string)(.|\en)*/$1/;
308 chop; s/.*(some_string).*/$1/;
309 /(some_string)/ && ($_ = $1);
312 Any item of a regular expression may be followed with digits in curly brackets
313 of the form {n,m}, where n gives the minimum number of times to match the item
314 and m gives the maximum.
315 The form {n} is equivalent to {n,n} and matches exactly n times.
316 The form {n,} matches n or more times.
317 (If a curly bracket occurs in any other context, it is treated as a regular
319 The * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
321 There is no limit to the size of n or m, but large numbers will chew up
324 You will note that all backslashed metacharacters in
327 such as \eb, \ew, \en.
328 Unlike some other regular expression languages, there are no backslashed
329 symbols that aren't alphanumeric.
330 So anything that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} is always
331 interpreted as a literal character, not a metacharacter.
332 This makes it simple to quote a string that you want to use for a pattern
333 but that you are afraid might contain metacharacters.
334 Simply quote all the non-alphanumeric characters:
337 $pattern =~ s/(\eW)/\e\e$1/g;
341 Output record formats for use with the
343 operator may declared as follows:
352 If name is omitted, format \*(L"STDOUT\*(R" is defined.
353 FORMLIST consists of a sequence of lines, each of which may be of one of three
358 A \*(L"picture\*(R" line giving the format for one output line.
360 An argument line supplying values to plug into a picture line.
362 Picture lines are printed exactly as they look, except for certain fields
363 that substitute values into the line.
364 Each picture field starts with either @ or ^.
365 The @ field (not to be confused with the array marker @) is the normal
366 case; ^ fields are used
367 to do rudimentary multi-line text block filling.
368 The length of the field is supplied by padding out the field
369 with multiple <, >, or | characters to specify, respectively, left justification,
370 right justification, or centering.
371 If any of the values supplied for these fields contains a newline, only
372 the text up to the newline is printed.
373 The special field @* can be used for printing multi-line values.
374 It should appear by itself on a line.
376 The values are specified on the following line, in the same order as
378 The values should be separated by commas.
380 Picture fields that begin with ^ rather than @ are treated specially.
381 The value supplied must be a scalar variable name which contains a text
384 puts as much text as it can into the field, and then chops off the front
385 of the string so that the next time the variable is referenced,
386 more of the text can be printed.
387 Normally you would use a sequence of fields in a vertical stack to print
389 If you like, you can end the final field with .\|.\|., which will appear in the
390 output if the text was too long to appear in its entirety.
391 You can change which characters are legal to break on by changing the
392 variable $: to a list of the desired characters.
394 Since use of ^ fields can produce variable length records if the text to be
395 formatted is short, you can suppress blank lines by putting the tilde (~)
396 character anywhere in the line.
397 (Normally you should put it in the front if possible, for visibility.)
398 The tilde will be translated to a space upon output.
399 If you put a second tilde contiguous to the first, the line will be repeated
400 until all the fields on the line are exhausted.
401 (If you use a field of the @ variety, the expression you supply had better
402 not give the same value every time forever!)
411 # a report on the /etc/passwd file
414 Name Login Office Uid Gid Home
415 ------------------------------------------------------------------
418 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
419 $name, $login, $office,$uid,$gid, $home
423 # a report from a bug report form
426 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
428 ------------------------------------------------------------------
431 Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
433 Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
434 \& $index, $description
435 Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
436 \& $priority, $date, $description
437 From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
438 \& $from, $description
439 Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
440 \& $programmer, $description
441 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
443 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
445 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
447 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
449 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<...
457 It is possible to intermix prints with writes on the same output channel,
458 but you'll have to handle $\- (lines left on the page) yourself.
460 If you are printing lots of fields that are usually blank, you should consider
461 using the reset operator between records.
462 Not only is it more efficient, but it can prevent the bug of adding another
463 field and forgetting to zero it.
464 .Sh "Interprocess Communication"
465 The IPC facilities of perl are built on the Berkeley socket mechanism.
466 If you don't have sockets, you can ignore this section.
467 The calls have the same names as the corresponding system calls,
468 but the arguments tend to differ, for two reasons.
469 First, perl file handles work differently than C file descriptors.
470 Second, perl already knows the length of its strings, so you don't need
471 to pass that information.
472 Here is a sample client (untested):
475 ($them,$port) = @ARGV;
476 $port = 2345 unless $port;
477 $them = 'localhost' unless $them;
479 $SIG{'INT'} = 'dokill';
480 sub dokill { kill 9,$child if $child; }
482 do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
484 $sockaddr = 'S n a4 x8';
485 chop($hostname = `hostname`);
487 ($name, $aliases, $proto) = getprotobyname('tcp');
488 ($name, $aliases, $port) = getservbyname($port, 'tcp')
489 unless $port =~ /^\ed+$/;;
491 ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
494 ($name, $aliases, $type, $len, $thisaddr) =
495 gethostbyname($hostname);
497 ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
499 $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
500 $that = pack($sockaddr, &AF_INET, $port, $thataddr);
502 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
503 bind(S, $this) || die "bind: $!";
504 connect(S, $that) || die "connect: $!";
506 select(S); $| = 1; select(stdout);
526 $port = 2345 unless $port;
528 do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
530 $sockaddr = 'S n a4 x8';
532 ($name, $aliases, $proto) = getprotobyname('tcp');
533 ($name, $aliases, $port) = getservbyname($port, 'tcp')
534 unless $port =~ /^\ed+$/;;
536 $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
538 select(NS); $| = 1; select(stdout);
540 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
541 bind(S, $this) || die "bind: $!";
542 listen(S, 5) || die "connect: $!";
544 select(S); $| = 1; select(stdout);
547 print "Listening again\en";
548 ($addr = accept(NS,S)) || die $!;
549 print "accept ok\en";
551 ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
552 @inetaddr = unpack('C4',$inetaddr);
553 print "$af $port @inetaddr\en";
562 .Sh "Predefined Names"
563 The following names have special meaning to
565 I could have used alphabetic symbols for some of these, but I didn't want
566 to take the chance that someone would say reset \*(L"a\-zA\-Z\*(R" and wipe them all
568 You'll just have to suffer along with these silly symbols.
569 Most of them have reasonable mnemonics, or analogues in one of the shells.
571 The default input and pattern-searching space.
572 The following pairs are equivalent:
576 while (<>) {\|.\|.\|. # only equivalent in while!
577 while ($_ = <>) {\|.\|.\|.
581 $_ \|=~ \|/\|^Subject:/
592 (Mnemonic: underline is understood in certain operations.)
594 The current input line number of the last filehandle that was read.
596 Remember that only an explicit close on the filehandle resets the line number.
597 Since <> never does an explicit close, line numbers increase across ARGV files
598 (but see examples under eof).
599 (Mnemonic: many programs use . to mean the current line number.)
601 The input record separator, newline by default.
604 RS variable, including treating blank lines as delimiters
605 if set to the null string.
606 If set to a value longer than one character, only the first character is used.
607 (Mnemonic: / is used to delimit line boundaries when quoting poetry.)
609 The output field separator for the print operator.
610 Ordinarily the print operator simply prints out the comma separated fields
612 In order to get behavior more like
614 set this variable as you would set
616 OFS variable to specify what is printed between fields.
617 (Mnemonic: what is printed when there is a , in your print statement.)
619 This is like $, except that it applies to array values interpolated into
620 a double-quoted string (or similar interpreted string).
622 (Mnemonic: obvious, I think.)
624 The output record separator for the print operator.
625 Ordinarily the print operator simply prints out the comma separated fields
626 you specify, with no trailing newline or record separator assumed.
627 In order to get behavior more like
629 set this variable as you would set
631 ORS variable to specify what is printed at the end of the print.
632 (Mnemonic: you set $\e instead of adding \en at the end of the print.
633 Also, it's just like /, but it's what you get \*(L"back\*(R" from
636 The output format for printed numbers.
637 This variable is a half-hearted attempt to emulate
640 There are times, however, when
644 have differing notions of what
646 Also, the initial value is %.20g rather than %.6g, so you need to set $#
650 (Mnemonic: # is the number sign.)
652 The current page number of the currently selected output channel.
653 (Mnemonic: % is page number in nroff.)
655 The current page length (printable lines) of the currently selected output
658 (Mnemonic: = has horizontal lines.)
660 The number of lines left on the page of the currently selected output channel.
661 (Mnemonic: lines_on_page \- lines_printed.)
663 The name of the current report format for the currently selected output
665 (Mnemonic: brother to $^.)
667 The name of the current top-of-page format for the currently selected output
669 (Mnemonic: points to top of page.)
671 If set to nonzero, forces a flush after every write or print on the currently
672 selected output channel.
676 will typically be line buffered if output is to the
677 terminal and block buffered otherwise.
678 Setting this variable is useful primarily when you are outputting to a pipe,
679 such as when you are running a
681 script under rsh and want to see the
682 output as it's happening.
683 (Mnemonic: when you want your pipes to be piping hot.)
685 The process number of the
688 (Mnemonic: same as shells.)
690 The status returned by the last pipe close, backtick (\`\`) command or
693 Note that this is the status word returned by the wait() system
694 call, so the exit value of the subprocess is actually ($? >> 8).
695 $? & 255 gives which signal, if any, the process died from, and whether
696 there was a core dump.
697 (Mnemonic: similar to sh and ksh.)
699 The string matched by the last pattern match (not counting any matches hidden
700 within a BLOCK or eval enclosed by the current BLOCK).
701 (Mnemonic: like & in some editors.)
703 The string preceding whatever was matched by the last pattern match
704 (not counting any matches hidden within a BLOCK or eval enclosed by the current
706 (Mnemonic: \` often precedes a quoted string.)
708 The string following whatever was matched by the last pattern match
709 (not counting any matches hidden within a BLOCK or eval enclosed by the current
711 (Mnemonic: \' often follows a quoted string.)
718 print "$\`:$&:$\'\en"; # prints abc:def:ghi
722 The last bracket matched by the last search pattern.
723 This is useful if you don't know which of a set of alternative patterns
728 /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
731 (Mnemonic: be positive and forward looking.)
733 Set to 1 to do multiline matching within a string, 0 to tell
735 that it can assume that strings contain a single line, for the purpose
736 of optimizing pattern matches.
737 Pattern matches on strings containing multiple newlines can produce confusing
738 results when $* is 0.
740 (Mnemonic: * matches multiple things.)
742 Contains the name of the file containing the
744 script being executed.
745 The value should be copied elsewhere before any pattern matching happens, which
747 (Mnemonic: same as sh and ksh.)
749 Contains the subpattern from the corresponding set of parentheses in the last
750 pattern matched, not counting patterns matched in nested blocks that have
752 (Mnemonic: like \edigit.)
754 The index of the first element in an array, and of the first character in
756 Default is 0, but you could set it to 1 to make
761 when subscripting and when evaluating the index() and substr() functions.
762 (Mnemonic: [ begins subscripts.)
764 The string printed out when you say \*(L"perl -v\*(R".
765 It can be used to determine at the beginning of a script whether the perl
766 interpreter executing the script is in the right range of versions.
771 # see if getc is available
772 ($version,$patchlevel) =
773 $] =~ /(\ed+\e.\ed+).*\enPatch level: (\ed+)/;
774 print STDERR "(No filename completion available.)\en"
775 if $version * 1000 + $patchlevel < 2016;
778 (Mnemonic: Is this version of perl in the right bracket?)
780 The subscript separator for multi-dimensional array emulation.
781 If you refer to an associative array element as
787 $foo{join($;, $a, $b, $c)}
791 @foo{$a,$b,$c} # a slice--note the @
795 ($foo{$a},$foo{$b},$foo{$c})
798 Default is "\e034", the same as SUBSEP in
800 Note that if your keys contain binary data there might not be any safe
802 (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
803 Yeah, I know, it's pretty lame, but $, is already taken for something more
806 If used in a numeric context, yields the current value of errno, with all the
808 (This means that you shouldn't depend on the value of $! to be anything
809 in particular unless you've gotten a specific error return indicating a
811 If used in a string context, yields the corresponding system error string.
812 You can assign to $! in order to set errno
813 if, for instance, you want $! to return the string for error n, or you want
814 to set the exit value for the die operator.
815 (Mnemonic: What just went bang?)
817 The perl syntax error message from the last eval command.
818 If null, the last eval parsed and executed correctly (although the operations
819 you invoked may have failed in the normal fashion).
820 (Mnemonic: Where was the syntax error \*(L"at\*(R"?)
822 The real uid of this process.
823 (Mnemonic: it's the uid you came FROM, if you're running setuid.)
825 The effective uid of this process.
830 $< = $>; # set real uid to the effective uid
831 ($<,$>) = ($>,$<); # swap real and effective uid
834 (Mnemonic: it's the uid you went TO, if you're running setuid.)
835 Note: $< and $> can only be swapped on machines supporting setreuid().
837 The real gid of this process.
838 If you are on a machine that supports membership in multiple groups
839 simultaneously, gives a space separated list of groups you are in.
840 The first number is the one returned by getgid(), and the subsequent ones
841 by getgroups(), one of which may be the same as the first number.
842 (Mnemonic: parentheses are used to GROUP things.
843 The real gid is the group you LEFT, if you're running setgid.)
845 The effective gid of this process.
846 If you are on a machine that supports membership in multiple groups
847 simultaneously, gives a space separated list of groups you are in.
848 The first number is the one returned by getegid(), and the subsequent ones
849 by getgroups(), one of which may be the same as the first number.
850 (Mnemonic: parentheses are used to GROUP things.
851 The effective gid is the group that's RIGHT for you, if you're running setgid.)
853 Note: $<, $>, $( and $) can only be set on machines that support the
854 corresponding set[re][ug]id() routine.
855 $( and $) can only be swapped on machines supporting setregid().
857 The current set of characters after which a string may be broken to
858 fill continuation fields (starting with ^) in a format.
859 Default is "\ \en-", to break on whitespace or hyphens.
860 (Mnemonic: a \*(L"colon\*(R" in poetry is a part of a line.)
862 The array ARGV contains the command line arguments intended for the script.
863 Note that $#ARGV is the generally number of arguments minus one, since
864 $ARGV[0] is the first argument, NOT the command name.
865 See $0 for the command name.
867 The array INC contains the list of places to look for
870 evaluated by the \*(L"do EXPR\*(R" command.
871 It initially consists of the arguments to any
873 command line switches, followed
876 library, probably \*(L"/usr/local/lib/perl\*(R".
878 The associative array ENV contains your current environment.
879 Setting a value in ENV changes the environment for child processes.
881 The associative array SIG is used to set signal handlers for various signals.
886 sub handler { # 1st argument is signal name
888 print "Caught a SIG$sig\-\|\-shutting down\en";
893 $SIG{\'INT\'} = \'handler\';
894 $SIG{\'QUIT\'} = \'handler\';
896 $SIG{\'INT\'} = \'DEFAULT\'; # restore default action
897 $SIG{\'QUIT\'} = \'IGNORE\'; # ignore SIGQUIT
900 The SIG array only contains values for the signals actually set within
903 Perl provides a mechanism for alternate namespaces to protect packages from
904 stomping on each others variables.
905 By default, a perl script starts compiling into the package known as \*(L"main\*(R".
908 declaration, you can switch namespaces.
909 The scope of the package declaration is from the declaration itself to the end
910 of the enclosing block (the same scope as the local() operator).
911 Typically it would be the first declaration in a file to be included by
912 the \*(L"do FILE\*(R" operator.
913 You can switch into a package in more than one place; it merely influences
914 which symbol table is used by the compiler for the rest of that block.
915 You can refer to variables in other packages by prefixing the name with
916 the package name and a single quote.
917 If the package name is null, the \*(L"main\*(R" package as assumed.
918 Eval'ed strings are compiled in the package in which the eval was compiled
920 (Assignments to $SIG{}, however, assume the signal handler specified is in the
922 Qualify the signal handler name if you wish to have a signal handler in
924 For an example, examine perldb.pl in the perl library.
925 It initially switches to the DB package so that the debugger doesn't interfere
926 with variables in the script you are trying to debug.
927 At various points, however, it temporarily switches back to the main package
928 to evaluate various expressions in the context of the main package.
930 The symbol table for a package happens to be stored in the associative array
931 of that name prepended with an underscore.
932 The value in each entry of the associative array is
933 what you are referring to when you use the *name notation.
934 In fact, the following have the same effect (in package main, anyway),
935 though the first is more
936 efficient because it does the symbol table lookups at compile time:
941 local($_main{'foo'}) = $_main{'bar'};
944 You can use this to print out all the variables in a package, for instance.
945 Here is dumpvar.pl from the perl library:
952 \& local(*stab) = eval("*_$package");
953 \& while (($key,$val) = each(%stab)) {
955 \& local(*entry) = $val;
956 \& if (defined $entry) {
957 \& print "\e$$key = '$entry'\en";
960 \& if (defined @entry) {
961 \& print "\e@$key = (\en";
962 \& foreach $num ($[ .. $#entry) {
963 \& print " $num\et'",$entry[$num],"'\en";
968 \& if ($key ne "_$package" && defined %entry) {
969 \& print "\e%$key = (\en";
970 \& foreach $key (sort keys(%entry)) {
971 \& print " $key\et'",$entry{$key},"'\en";
980 Note that, even though the subroutine is compiled in package dumpvar, the
981 name of the subroutine is qualified so that it's name is inserted into package
984 Each programmer will, of course, have his or her own preferences in regards
985 to formatting, but there are some general guidelines that will make your
986 programs easier to read.
988 Just because you CAN do something a particular way doesn't mean that
989 you SHOULD do it that way.
991 is designed to give you several ways to do anything, so consider picking
992 the most readable one.
995 open(FOO,$foo) || die "Can't open $foo: $!";
999 die "Can't open $foo: $!" unless open(FOO,$foo);
1001 because the second way hides the main point of the statement in a
1005 print "Starting analysis\en" if $verbose;
1009 $verbose && print "Starting analysis\en";
1011 since the main point isn't whether the user typed -v or not.
1013 Similarly, just because an operator lets you assume default arguments
1014 doesn't mean that you have to make use of the defaults.
1015 The defaults are there for lazy systems programmers writing one-shot
1017 If you want your program to be readable, consider supplying the argument.
1019 Along the same lines, just because you
1021 omit parentheses in many places doesn't mean that you ought to:
1024 return print reverse sort num values array;
1025 return print(reverse(sort num (values(%array))));
1028 When in doubt, parenthesize.
1029 At the very least it will let some poor schmuck bounce on the % key in vi.
1031 Don't go through silly contortions to exit a loop at the top or the
1034 provides the "last" operator so you can exit in the middle.
1035 Just outdent it a little to make it more visible:
1049 Don't be afraid to use loop labels\*(--they're there to enhance readability as
1050 well as to allow multi-level loop breaks.
1053 For portability, when using features that may not be implemented on every
1054 machine, test the construct in an eval to see if it fails.
1055 If you know what version or patchlevel a particular feature was implemented,
1056 you can test $] to see if it will be there.
1058 Choose mnemonic identifiers.
1066 switch, your script will be run under a debugging monitor.
1067 It will halt before the first executable statement and ask you for a
1070 Prints out a help message.
1073 Executes until it reaches the beginning of another statement.
1076 Executes until the next breakpoint is reached.
1080 Single step around subroutine call.
1081 .Ip "l min+incr" 12 4
1082 List incr+1 lines starting at min.
1083 If min is omitted, starts where last listing left off.
1084 If incr is omitted, previous value of incr is used.
1085 .Ip "l min-max" 12 4
1086 List lines in the indicated range.
1088 List just the indicated line.
1090 List incr+1 more lines after last printed line.
1091 .Ip "l subname" 12 4
1093 If it's a long subroutine it just lists the beginning.
1094 Use \*(L"l\*(R" to list more.
1096 List lines that have breakpoints or actions.
1098 Toggle trace mode on or off.
1101 If line is omitted, sets a breakpoint on the current line
1102 line that is about to be executed.
1103 Breakpoints may only be set on lines that begin an executable statement.
1104 .Ip "b subname" 12 4
1105 Set breakpoint at first executable line of subroutine.
1107 Lists the names of all subroutines.
1110 If line is omitted, deletes the breakpoint on the current line
1111 line that is about to be executed.
1113 Delete all breakpoints.
1115 Delete all line actions.
1116 .Ip "V package" 12 4
1117 List all variables in package.
1118 Default is main package.
1119 .Ip "a line command" 12 4
1120 Set an action for line.
1121 A multi-line command may be entered by backslashing the newlines.
1122 .Ip "< command" 12 4
1123 Set an action to happen before every debugger prompt.
1124 A multi-line command may be entered by backslashing the newlines.
1125 .Ip "> command" 12 4
1126 Set an action to happen after the prompt when you've just given a command
1127 to return to executing the script.
1128 A multi-line command may be entered by backslashing the newlines.
1130 Redo a debugging command.
1131 If number is omitted, redoes the previous command.
1132 .Ip "! -number" 12 4
1133 Redo the command that was that many commands ago.
1134 .Ip "H -number" 12 4
1135 Display last n commands.
1136 Only commands longer than one character are listed.
1137 If number is omitted, lists them all.
1141 Execute command as a perl statement.
1142 A missing semicolon will be supplied.
1144 Same as \*(L"print DB'OUT expr\*(R".
1145 The DB'OUT filehandle is opened to /dev/tty, regardless of where STDOUT
1146 may be redirected to.
1148 If you want to modify the debugger, copy perldb.pl from the perl library
1149 to your current directory and modify it as necessary.
1150 You can do some customization by setting up a .perldb file which contains
1151 initialization code.
1152 For instance, you could make aliases like these:
1155 $DBalias{'len'} = 's/^len(.*)/p length(\e$1)/';
1156 $DBalias{'stop'} = 's/^stop (at|in)/b/';
1158 's/^./p "\e$DBsub(\e$DBline):\et\e$DBline[\e$DBline]"/';
1161 .Sh "Setuid Scripts"
1163 is designed to make it easy to write secure setuid and setgid scripts.
1164 Unlike shells, which are based on multiple substitution passes on each line
1167 uses a more conventional evaluation scheme with fewer hidden \*(L"gotchas\*(R".
1168 Additionally, since the language has more built-in functionality, it
1169 has to rely less upon external (and possibly untrustworthy) programs to
1170 accomplish its purposes.
1172 In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
1173 insecure, but this kernel feature can be disabled.
1176 can emulate the setuid and setgid mechanism when it notices the otherwise
1177 useless setuid/gid bits on perl scripts.
1178 If the kernel feature isn't disabled,
1180 will complain loudly that your setuid script is insecure.
1181 You'll need to either disable the kernel setuid script feature, or put
1182 a C wrapper around the script.
1184 When perl is executing a setuid script, it takes special precautions to
1185 prevent you from falling into any obvious traps.
1186 (In some ways, a perl script is more secure than the corresponding
1188 Any command line argument, environment variable, or input is marked as
1189 \*(L"tainted\*(R", and may not be used, directly or indirectly, in any
1190 command that invokes a subshell, or in any command that modifies files,
1191 directories or processes.
1192 Any variable that is set within an expression that has previously referenced
1193 a tainted value also becomes tainted (even if it is logically impossible
1194 for the tainted value to influence the variable).
1199 $foo = shift; # $foo is tainted
1200 $bar = $foo,\'bar\'; # $bar is also tainted
1201 $xxx = <>; # Tainted
1202 $path = $ENV{\'PATH\'}; # Tainted, but see below
1203 $abc = \'abc\'; # Not tainted
1206 system "echo $foo"; # Insecure
1207 system "echo", $foo; # Secure (doesn't use sh)
1208 system "echo $bar"; # Insecure
1209 system "echo $abc"; # Insecure until PATH set
1212 $ENV{\'PATH\'} = \'/bin:/usr/bin\';
1213 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1215 $path = $ENV{\'PATH\'}; # Not tainted
1216 system "echo $abc"; # Is secure now!
1219 open(FOO,"$foo"); # OK
1220 open(FOO,">$foo"); # Not OK
1222 open(FOO,"echo $foo|"); # Not OK, but...
1223 open(FOO,"-|") || exec \'echo\', $foo; # OK
1225 $zzz = `echo $foo`; # Insecure, zzz tainted
1227 unlink $abc,$foo; # Insecure
1228 umask $foo; # Insecure
1231 exec "echo $foo"; # Insecure
1232 exec "echo", $foo; # Secure (doesn't use sh)
1233 exec "sh", \'-c\', $foo; # Considered secure, alas
1236 The taintedness is associated with each scalar value, so some elements
1237 of an array can be tainted, and others not.
1239 If you try to do something insecure, you will get a fatal error saying
1240 something like \*(L"Insecure dependency\*(R" or \*(L"Insecure PATH\*(R".
1241 Note that you can still write an insecure system call or exec,
1242 but only by explicitly doing something like the last example above.
1243 You can also bypass the tainting mechanism by referencing
1246 presumes that if you reference a substring using $1, $2, etc, you knew
1247 what you were doing when you wrote the pattern:
1250 $ARGV[0] =~ /^\-P(\ew+)$/;
1251 $printer = $1; # Not tainted
1254 This is fairly secure since \ew+ doesn't match shell metacharacters.
1255 Use of .+ would have been insecure, but
1257 doesn't check for that, so you must be careful with your patterns.
1258 This is the ONLY mechanism for untainting user supplied filenames if you
1259 want to do file operations on them (unless you make $> equal to $<).
1261 It's also possible to get into trouble with other operations that don't care
1262 whether they use tainted values.
1263 Make judicious use of the file tests in dealing with any user-supplied
1265 When possible, do opens and such after setting $> = $<.
1267 doesn't prevent you from opening tainted filenames for reading, so be
1268 careful what you print out.
1269 The tainting mechanism is intended to prevent stupid mistakes, not to remove
1270 the need for thought.
1273 uses PATH in executing subprocesses, and in finding the script if \-S
1275 HOME or LOGDIR are used if chdir has no argument.
1279 uses no environment variables, except to make them available
1280 to the script being executed, and to child processes.
1281 However, scripts running setuid would do well to execute the following lines
1282 before doing anything else, just to keep people honest:
1286 $ENV{\'PATH\'} = \'/bin:/usr/bin\'; # or whatever you need
1287 $ENV{\'SHELL\'} = \'/bin/sh\' if $ENV{\'SHELL\'} ne \'\';
1288 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1292 Larry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
1294 /tmp/perl\-eXXXXXX temporary file for
1298 a2p awk to perl translator
1300 s2p sed to perl translator
1302 Compilation errors will tell you the line number of the error, with an
1303 indication of the next token or token type that was to be examined.
1304 (In the case of a script passed to
1310 is counted as one line.)
1312 Setuid scripts have additional constraints that can produce error messages
1313 such as \*(L"Insecure dependency\*(R".
1314 See the section on setuid scripts.
1318 users should take special note of the following:
1320 Semicolons are required after all simple statements in
1323 is not a statement delimiter.
1325 Curly brackets are required on ifs and whiles.
1327 Variables begin with $ or @ in
1330 Arrays index from 0 unless you set $[.
1331 Likewise string positions in substr() and index().
1333 You have to decide whether your array has numeric or string indices.
1335 Associative array values do not spring into existence upon mere reference.
1337 You have to decide whether you want to use string or numeric comparisons.
1339 Reading an input line does not split it for you. You get to split it yourself
1343 operator has different arguments.
1345 The current input line is normally in $_, not $0.
1346 It generally does not have the newline stripped.
1347 ($0 is initially the name of the program executed, then the last matched
1350 $<digit> does not refer to fields\*(--it refers to substrings matched by the last
1355 statement does not add field and record separators unless you set
1358 You must open your files before you print to them.
1360 The range operator is \*(L".\|.\*(R", not comma.
1361 (The comma operator works as in C.)
1363 The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
1364 (\*(L"~\*(R" is the one's complement operator, as in C.)
1366 The exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
1367 (\*(L"^\*(R" is the XOR operator, as in C.)
1369 The concatenation operator is \*(L".\*(R", not the null string.
1370 (Using the null string would render \*(L"/pat/ /pat/\*(R" unparsable,
1371 since the third slash would be interpreted as a division operator\*(--the
1372 tokener is in fact slightly context sensitive for operators like /, ?, and <.
1373 And in fact, . itself can be the beginning of a number.)
1381 The following variables work differently
1385 ARGC \h'|2.5i'$#ARGV
1387 FILENAME\h'|2.5i'$ARGV
1388 FNR \h'|2.5i'$. \- something
1389 FS \h'|2.5i'(whatever you like)
1390 NF \h'|2.5i'$#Fld, or some such
1395 RLENGTH \h'|2.5i'length($&)
1397 RSTART \h'|2.5i'length($\`)
1402 When in doubt, run the
1404 construct through a2p and see what it gives you.
1406 Cerebral C programmers should take note of the following:
1408 Curly brackets are required on ifs and whiles.
1410 You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
1421 There's no switch statement.
1423 Variables begin with $ or @ in
1426 Printf does not implement *.
1428 Comments begin with #, not /*.
1430 You can't take the address of anything.
1432 ARGV must be capitalized.
1434 The \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
1436 Signal handlers deal with signal names, not numbers.
1438 You can't subscript array values, only arrays (no $x = (1,2,3)[2];).
1442 programmers should take note of the following:
1444 Backreferences in substitutions use $ rather than \e.
1446 The pattern matching metacharacters (, ), and | do not have backslashes in front.
1448 The range operator is .\|. rather than comma.
1450 Sharp shell programmers should take note of the following:
1452 The backtick operator does variable interpretation without regard to the
1453 presence of single quotes in the command.
1455 The backtick operator does no translation of the return value, unlike csh.
1457 Shells (especially csh) do several levels of substitution on each command line.
1459 does substitution only in certain constructs such as double quotes,
1460 backticks, angle brackets and search patterns.
1462 Shells interpret scripts a little bit at a time.
1464 compiles the whole program before executing it.
1466 The arguments are available via @ARGV, not $1, $2, etc.
1468 The environment is not automatically made available as variables.
1472 is at the mercy of your machine's definitions of various operations
1473 such as type casting, atof() and sprintf().
1475 If your stdio requires an seek or eof between reads and writes on a particular
1479 While none of the built-in data types have any arbitrary size limits (apart
1480 from memory size), there are still a few arbitrary limits:
1481 a given identifier may not be longer than 255 characters;
1482 sprintf is limited on many machines to 128 characters per field (unless the format
1483 specifier is exactly %s);
1484 and no component of your PATH may be longer than 255 if you use \-S.
1487 actually stands for Pathologically Eclectic Rubbish Lister, but don't tell