1 ''' Beginning of part 4
2 ''' $Header: perl.man.4,v 3.0.1.7 90/03/14 12:29:50 lwall Locked $
4 ''' $Log: perl.man.4,v $
5 ''' Revision 3.0.1.7 90/03/14 12:29:50 lwall
6 ''' patch15: man page falsely states that you can't subscript array values
8 ''' Revision 3.0.1.6 90/03/12 16:54:04 lwall
9 ''' patch13: improved documentation of *name
11 ''' Revision 3.0.1.5 90/02/28 18:01:52 lwall
12 ''' patch9: $0 is now always the command name
14 ''' Revision 3.0.1.4 89/12/21 20:12:39 lwall
15 ''' patch7: documented that package'filehandle works as well as $package'variable
16 ''' patch7: documented which identifiers are always in package main
18 ''' Revision 3.0.1.3 89/11/17 15:32:25 lwall
19 ''' patch5: fixed some manual typos and indent problems
20 ''' patch5: clarified difference between $! and $@
22 ''' Revision 3.0.1.2 89/11/11 04:46:40 lwall
23 ''' patch2: made some line breaks depend on troff vs. nroff
24 ''' patch2: clarified operation of ^ and $ when $* is false
26 ''' Revision 3.0.1.1 89/10/26 23:18:43 lwall
27 ''' patch1: documented the desirability of unnecessary parentheses
29 ''' Revision 3.0 89/10/18 15:21:55 lwall
34 operators have the following associativity and precedence:
37 nonassoc\h'|1i'print printf exec system sort reverse
38 \h'1.5i'chmod chown kill unlink utime die return
40 right\h'|1i'= += \-= *= etc.
47 nonassoc\h'|1i'== != eq ne
48 nonassoc\h'|1i'< > <= >= lt gt le ge
49 nonassoc\h'|1i'chdir exit eval reset sleep rand umask
50 nonassoc\h'|1i'\-r \-w \-x etc.
55 right\h'|1i'! ~ and unary minus
57 nonassoc\h'|1i'++ \-\|\-
58 left\h'|1i'\*(L'(\*(R'
61 As mentioned earlier, if any list operator (print, etc.) or
62 any unary operator (chdir, etc.)
63 is followed by a left parenthesis as the next token on the same line,
64 the operator and arguments within parentheses are taken to
65 be of highest precedence, just like a normal function call.
69 chdir $foo || die;\h'|3i'# (chdir $foo) || die
70 chdir($foo) || die;\h'|3i'# (chdir $foo) || die
71 chdir ($foo) || die;\h'|3i'# (chdir $foo) || die
72 chdir +($foo) || die;\h'|3i'# (chdir $foo) || die
74 but, because * is higher precedence than ||:
76 chdir $foo * 20;\h'|3i'# chdir ($foo * 20)
77 chdir($foo) * 20;\h'|3i'# (chdir $foo) * 20
78 chdir ($foo) * 20;\h'|3i'# (chdir $foo) * 20
79 chdir +($foo) * 20;\h'|3i'# chdir ($foo * 20)
81 rand 10 * 20;\h'|3i'# rand (10 * 20)
82 rand(10) * 20;\h'|3i'# (rand 10) * 20
83 rand (10) * 20;\h'|3i'# (rand 10) * 20
84 rand +(10) * 20;\h'|3i'# rand (10 * 20)
87 In the absence of parentheses,
88 the precedence of list operators such as print, sort or chmod is
89 either very high or very low depending on whether you look at the left
90 side of operator or the right side of it.
94 @ary = (1, 3, sort 4, 2);
95 print @ary; # prints 1324
98 the commas on the right of the sort are evaluated before the sort, but
99 the commas on the left are evaluated after.
100 In other words, list operators tend to gobble up all the arguments that
101 follow them, and then act like a simple term with regard to the preceding
103 Note that you have to be careful with parens:
107 # These evaluate exit before doing the print:
108 print($foo, exit); # Obviously not what you want.
109 print $foo, exit; # Nor is this.
112 # These do the print before evaluating exit:
113 (print $foo), exit; # This is what you want.
114 print($foo), exit; # Or this.
115 print ($foo), exit; # Or even this.
119 print ($foo & 255) + 1, "\en";
122 probably doesn't do what you expect at first glance.
124 A subroutine may be declared as follows:
131 Any arguments passed to the routine come in as array @_,
132 that is ($_[0], $_[1], .\|.\|.).
133 The array @_ is a local array, but its values are references to the
134 actual scalar parameters.
135 The return value of the subroutine is the value of the last expression
136 evaluated, and can be either an array value or a scalar value.
137 Alternately, a return statement may be used to specify the returned value and
139 To create local variables see the
143 A subroutine is called using the
145 operator or the & operator.
152 local($max) = pop(@_);
154 $max = $foo \|if \|$max < $foo;
160 $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
165 # get a line, combining continuation lines
166 # that start with whitespace
168 $thisline = $lookahead;
169 line: while ($lookahead = <STDIN>) {
170 if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
171 $thisline \|.= \|$lookahead;
180 $lookahead = <STDIN>; # get first line
181 while ($_ = do get_line(\|)) {
188 Use array assignment to a local list to name your formal arguments:
191 local($key, $value) = @_;
192 $foo{$key} = $value unless $foo{$key};
196 This also has the effect of turning call-by-reference into call-by-value,
197 since the assignment copies the values.
199 Subroutines may be called recursively.
200 If a subroutine is called using the & form, the argument list is optional.
201 If omitted, no @_ array is set up for the subroutine; the @_ array at the
202 time of the call is visible to subroutine instead.
205 do foo(1,2,3); # pass three arguments
206 &foo(1,2,3); # the same
208 do foo(); # pass a null list
210 &foo; # pass no arguments--more efficient
213 .Sh "Passing By Reference"
214 Sometimes you don't want to pass the value of an array to a subroutine but
215 rather the name of it, so that the subroutine can modify the global copy
216 of it rather than working with a local copy.
217 In perl you can refer to all the objects of a particular name by prefixing
218 the name with a star: *foo.
219 When evaluated, it produces a scalar value that represents all the objects
220 of that name, including any filehandle, format or subroutine.
221 When assigned to within a local() operation, it causes the name mentioned
222 to refer to whatever * value was assigned to it.
227 local(*someary) = @_;
228 foreach $elem (@someary) {
236 Assignment to *name is currently recommended only inside a local().
237 You can actually assign to *name anywhere, but the previous referent of
238 *name may be stranded forever.
239 This may or may not bother you.
241 Note that scalars are already passed by reference, so you can modify scalar
242 arguments without using this mechanism by referring explicitly to the $_[nnn]
244 You can modify all the elements of an array by passing all the elements
245 as scalars, but you have to use the * mechanism to push, pop or change the
247 The * mechanism will probably be more efficient in any case.
249 Since a *name value contains unprintable binary data, if it is used as
250 an argument in a print, or as a %s argument in a printf or sprintf, it
251 then has the value '*name', just so it prints out pretty.
253 Even if you don't want to modify an array, this mechanism is useful for
254 passing multiple arrays in a single LIST, since normally the LIST mechanism
255 will merge all the array values so that you can't extract out the
257 .Sh "Regular Expressions"
258 The patterns used in pattern matching are regular expressions such as
259 those supplied in the Version 8 regexp routines.
260 (In fact, the routines are derived from Henry Spencer's freely redistributable
261 reimplementation of the V8 routines.)
262 In addition, \ew matches an alphanumeric character (including \*(L"_\*(R") and \eW a nonalphanumeric.
263 Word boundaries may be matched by \eb, and non-boundaries by \eB.
264 A whitespace character is matched by \es, non-whitespace by \eS.
265 A numeric character is matched by \ed, non-numeric by \eD.
266 You may use \ew, \es and \ed within character classes.
267 Also, \en, \er, \ef, \et and \eNNN have their normal interpretations.
268 Within character classes \eb represents backspace rather than a word boundary.
269 Alternatives may be separated by |.
270 The bracketing construct \|(\ .\|.\|.\ \|) may also be used, in which case \e<digit>
271 matches the digit'th substring, where digit can range from 1 to 9.
272 (Outside of the pattern, always use $ instead of \e in front of the digit.
273 The scope of $<digit> (and $\`, $& and $\')
274 extends to the end of the enclosing BLOCK or eval string, or to
275 the next pattern match with subexpressions.
276 The \e<digit> notation sometimes works outside the current pattern, but should
278 $+ returns whatever the last bracket match matched.
279 $& returns the entire matched string.
280 ($0 used to return the same thing, but not any more.)
281 $\` returns everything before the matched string.
282 $\' returns everything after the matched string.
286 s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/; # swap first two words
289 if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
296 By default, the ^ character is only guaranteed to match at the beginning
298 the $ character only at the end (or before the newline at the end)
301 does certain optimizations with the assumption that the string contains
303 The behavior of ^ and $ on embedded newlines will be inconsistent.
304 You may, however, wish to treat a string as a multi-line buffer, such that
305 the ^ will match after any newline within the string, and $ will match
307 At the cost of a little more overhead, you can do this by setting the variable
309 Setting it back to 0 makes
311 revert to its old behavior.
313 To facilitate multi-line substitutions, the . character never matches a newline
315 In particular, the following leaves a newline on the $_ string:
319 s/.*(some_string).*/$1/;
321 If the newline is unwanted, try one of
323 s/.*(some_string).*\en/$1/;
324 s/.*(some_string)[^\e000]*/$1/;
325 s/.*(some_string)(.|\en)*/$1/;
326 chop; s/.*(some_string).*/$1/;
327 /(some_string)/ && ($_ = $1);
330 Any item of a regular expression may be followed with digits in curly brackets
331 of the form {n,m}, where n gives the minimum number of times to match the item
332 and m gives the maximum.
333 The form {n} is equivalent to {n,n} and matches exactly n times.
334 The form {n,} matches n or more times.
335 (If a curly bracket occurs in any other context, it is treated as a regular
337 The * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
339 There is no limit to the size of n or m, but large numbers will chew up
342 You will note that all backslashed metacharacters in
345 such as \eb, \ew, \en.
346 Unlike some other regular expression languages, there are no backslashed
347 symbols that aren't alphanumeric.
348 So anything that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} is always
349 interpreted as a literal character, not a metacharacter.
350 This makes it simple to quote a string that you want to use for a pattern
351 but that you are afraid might contain metacharacters.
352 Simply quote all the non-alphanumeric characters:
355 $pattern =~ s/(\eW)/\e\e$1/g;
359 Output record formats for use with the
361 operator may declared as follows:
370 If name is omitted, format \*(L"STDOUT\*(R" is defined.
371 FORMLIST consists of a sequence of lines, each of which may be of one of three
376 A \*(L"picture\*(R" line giving the format for one output line.
378 An argument line supplying values to plug into a picture line.
380 Picture lines are printed exactly as they look, except for certain fields
381 that substitute values into the line.
382 Each picture field starts with either @ or ^.
383 The @ field (not to be confused with the array marker @) is the normal
384 case; ^ fields are used
385 to do rudimentary multi-line text block filling.
386 The length of the field is supplied by padding out the field
387 with multiple <, >, or | characters to specify, respectively, left justification,
388 right justification, or centering.
389 If any of the values supplied for these fields contains a newline, only
390 the text up to the newline is printed.
391 The special field @* can be used for printing multi-line values.
392 It should appear by itself on a line.
394 The values are specified on the following line, in the same order as
396 The values should be separated by commas.
398 Picture fields that begin with ^ rather than @ are treated specially.
399 The value supplied must be a scalar variable name which contains a text
402 puts as much text as it can into the field, and then chops off the front
403 of the string so that the next time the variable is referenced,
404 more of the text can be printed.
405 Normally you would use a sequence of fields in a vertical stack to print
407 If you like, you can end the final field with .\|.\|., which will appear in the
408 output if the text was too long to appear in its entirety.
409 You can change which characters are legal to break on by changing the
410 variable $: to a list of the desired characters.
412 Since use of ^ fields can produce variable length records if the text to be
413 formatted is short, you can suppress blank lines by putting the tilde (~)
414 character anywhere in the line.
415 (Normally you should put it in the front if possible, for visibility.)
416 The tilde will be translated to a space upon output.
417 If you put a second tilde contiguous to the first, the line will be repeated
418 until all the fields on the line are exhausted.
419 (If you use a field of the @ variety, the expression you supply had better
420 not give the same value every time forever!)
429 # a report on the /etc/passwd file
432 Name Login Office Uid Gid Home
433 ------------------------------------------------------------------
436 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
437 $name, $login, $office,$uid,$gid, $home
441 # a report from a bug report form
444 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
446 ------------------------------------------------------------------
449 Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
451 Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
452 \& $index, $description
453 Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
454 \& $priority, $date, $description
455 From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
456 \& $from, $description
457 Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
458 \& $programmer, $description
459 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
461 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
463 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
465 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
467 \&~ ^<<<<<<<<<<<<<<<<<<<<<<<...
475 It is possible to intermix prints with writes on the same output channel,
476 but you'll have to handle $\- (lines left on the page) yourself.
478 If you are printing lots of fields that are usually blank, you should consider
479 using the reset operator between records.
480 Not only is it more efficient, but it can prevent the bug of adding another
481 field and forgetting to zero it.
482 .Sh "Interprocess Communication"
483 The IPC facilities of perl are built on the Berkeley socket mechanism.
484 If you don't have sockets, you can ignore this section.
485 The calls have the same names as the corresponding system calls,
486 but the arguments tend to differ, for two reasons.
487 First, perl file handles work differently than C file descriptors.
488 Second, perl already knows the length of its strings, so you don't need
489 to pass that information.
490 Here is a sample client (untested):
493 ($them,$port) = @ARGV;
494 $port = 2345 unless $port;
495 $them = 'localhost' unless $them;
497 $SIG{'INT'} = 'dokill';
498 sub dokill { kill 9,$child if $child; }
500 do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
502 $sockaddr = 'S n a4 x8';
503 chop($hostname = `hostname`);
505 ($name, $aliases, $proto) = getprotobyname('tcp');
506 ($name, $aliases, $port) = getservbyname($port, 'tcp')
507 unless $port =~ /^\ed+$/;;
509 ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
512 ($name, $aliases, $type, $len, $thisaddr) =
513 gethostbyname($hostname);
515 ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
517 $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
518 $that = pack($sockaddr, &AF_INET, $port, $thataddr);
520 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
521 bind(S, $this) || die "bind: $!";
522 connect(S, $that) || die "connect: $!";
524 select(S); $| = 1; select(stdout);
544 $port = 2345 unless $port;
546 do 'sys/socket.h' || die "Can't do sys/socket.h: $@";
548 $sockaddr = 'S n a4 x8';
550 ($name, $aliases, $proto) = getprotobyname('tcp');
551 ($name, $aliases, $port) = getservbyname($port, 'tcp')
552 unless $port =~ /^\ed+$/;;
554 $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
556 select(NS); $| = 1; select(stdout);
558 socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
559 bind(S, $this) || die "bind: $!";
560 listen(S, 5) || die "connect: $!";
562 select(S); $| = 1; select(stdout);
565 print "Listening again\en";
566 ($addr = accept(NS,S)) || die $!;
567 print "accept ok\en";
569 ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
570 @inetaddr = unpack('C4',$inetaddr);
571 print "$af $port @inetaddr\en";
580 .Sh "Predefined Names"
581 The following names have special meaning to
583 I could have used alphabetic symbols for some of these, but I didn't want
584 to take the chance that someone would say reset \*(L"a\-zA\-Z\*(R" and wipe them all
586 You'll just have to suffer along with these silly symbols.
587 Most of them have reasonable mnemonics, or analogues in one of the shells.
589 The default input and pattern-searching space.
590 The following pairs are equivalent:
594 while (<>) {\|.\|.\|. # only equivalent in while!
595 while ($_ = <>) {\|.\|.\|.
599 $_ \|=~ \|/\|^Subject:/
610 (Mnemonic: underline is understood in certain operations.)
612 The current input line number of the last filehandle that was read.
614 Remember that only an explicit close on the filehandle resets the line number.
615 Since <> never does an explicit close, line numbers increase across ARGV files
616 (but see examples under eof).
617 (Mnemonic: many programs use . to mean the current line number.)
619 The input record separator, newline by default.
622 RS variable, including treating blank lines as delimiters
623 if set to the null string.
624 If set to a value longer than one character, only the first character is used.
625 (Mnemonic: / is used to delimit line boundaries when quoting poetry.)
627 The output field separator for the print operator.
628 Ordinarily the print operator simply prints out the comma separated fields
630 In order to get behavior more like
632 set this variable as you would set
634 OFS variable to specify what is printed between fields.
635 (Mnemonic: what is printed when there is a , in your print statement.)
637 This is like $, except that it applies to array values interpolated into
638 a double-quoted string (or similar interpreted string).
640 (Mnemonic: obvious, I think.)
642 The output record separator for the print operator.
643 Ordinarily the print operator simply prints out the comma separated fields
644 you specify, with no trailing newline or record separator assumed.
645 In order to get behavior more like
647 set this variable as you would set
649 ORS variable to specify what is printed at the end of the print.
650 (Mnemonic: you set $\e instead of adding \en at the end of the print.
651 Also, it's just like /, but it's what you get \*(L"back\*(R" from
654 The output format for printed numbers.
655 This variable is a half-hearted attempt to emulate
658 There are times, however, when
662 have differing notions of what
664 Also, the initial value is %.20g rather than %.6g, so you need to set $#
668 (Mnemonic: # is the number sign.)
670 The current page number of the currently selected output channel.
671 (Mnemonic: % is page number in nroff.)
673 The current page length (printable lines) of the currently selected output
676 (Mnemonic: = has horizontal lines.)
678 The number of lines left on the page of the currently selected output channel.
679 (Mnemonic: lines_on_page \- lines_printed.)
681 The name of the current report format for the currently selected output
683 (Mnemonic: brother to $^.)
685 The name of the current top-of-page format for the currently selected output
687 (Mnemonic: points to top of page.)
689 If set to nonzero, forces a flush after every write or print on the currently
690 selected output channel.
694 will typically be line buffered if output is to the
695 terminal and block buffered otherwise.
696 Setting this variable is useful primarily when you are outputting to a pipe,
697 such as when you are running a
699 script under rsh and want to see the
700 output as it's happening.
701 (Mnemonic: when you want your pipes to be piping hot.)
703 The process number of the
706 (Mnemonic: same as shells.)
708 The status returned by the last pipe close, backtick (\`\`) command or
711 Note that this is the status word returned by the wait() system
712 call, so the exit value of the subprocess is actually ($? >> 8).
713 $? & 255 gives which signal, if any, the process died from, and whether
714 there was a core dump.
715 (Mnemonic: similar to sh and ksh.)
717 The string matched by the last pattern match (not counting any matches hidden
718 within a BLOCK or eval enclosed by the current BLOCK).
719 (Mnemonic: like & in some editors.)
721 The string preceding whatever was matched by the last pattern match
722 (not counting any matches hidden within a BLOCK or eval enclosed by the current
724 (Mnemonic: \` often precedes a quoted string.)
726 The string following whatever was matched by the last pattern match
727 (not counting any matches hidden within a BLOCK or eval enclosed by the current
729 (Mnemonic: \' often follows a quoted string.)
736 print "$\`:$&:$\'\en"; # prints abc:def:ghi
740 The last bracket matched by the last search pattern.
741 This is useful if you don't know which of a set of alternative patterns
746 /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
749 (Mnemonic: be positive and forward looking.)
751 Set to 1 to do multiline matching within a string, 0 to tell
753 that it can assume that strings contain a single line, for the purpose
754 of optimizing pattern matches.
755 Pattern matches on strings containing multiple newlines can produce confusing
756 results when $* is 0.
758 (Mnemonic: * matches multiple things.)
760 Contains the name of the file containing the
762 script being executed.
763 (Mnemonic: same as sh and ksh.)
765 Contains the subpattern from the corresponding set of parentheses in the last
766 pattern matched, not counting patterns matched in nested blocks that have
768 (Mnemonic: like \edigit.)
770 The index of the first element in an array, and of the first character in
772 Default is 0, but you could set it to 1 to make
777 when subscripting and when evaluating the index() and substr() functions.
778 (Mnemonic: [ begins subscripts.)
780 The string printed out when you say \*(L"perl -v\*(R".
781 It can be used to determine at the beginning of a script whether the perl
782 interpreter executing the script is in the right range of versions.
787 # see if getc is available
788 ($version,$patchlevel) =
789 $] =~ /(\ed+\e.\ed+).*\enPatch level: (\ed+)/;
790 print STDERR "(No filename completion available.)\en"
791 if $version * 1000 + $patchlevel < 2016;
794 (Mnemonic: Is this version of perl in the right bracket?)
796 The subscript separator for multi-dimensional array emulation.
797 If you refer to an associative array element as
803 $foo{join($;, $a, $b, $c)}
807 @foo{$a,$b,$c} # a slice--note the @
811 ($foo{$a},$foo{$b},$foo{$c})
814 Default is "\e034", the same as SUBSEP in
816 Note that if your keys contain binary data there might not be any safe
818 (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
819 Yeah, I know, it's pretty lame, but $, is already taken for something more
822 If used in a numeric context, yields the current value of errno, with all the
824 (This means that you shouldn't depend on the value of $! to be anything
825 in particular unless you've gotten a specific error return indicating a
827 If used in a string context, yields the corresponding system error string.
828 You can assign to $! in order to set errno
829 if, for instance, you want $! to return the string for error n, or you want
830 to set the exit value for the die operator.
831 (Mnemonic: What just went bang?)
833 The perl syntax error message from the last eval command.
834 If null, the last eval parsed and executed correctly (although the operations
835 you invoked may have failed in the normal fashion).
836 (Mnemonic: Where was the syntax error \*(L"at\*(R"?)
838 The real uid of this process.
839 (Mnemonic: it's the uid you came FROM, if you're running setuid.)
841 The effective uid of this process.
846 $< = $>; # set real uid to the effective uid
847 ($<,$>) = ($>,$<); # swap real and effective uid
850 (Mnemonic: it's the uid you went TO, if you're running setuid.)
851 Note: $< and $> can only be swapped on machines supporting setreuid().
853 The real gid of this process.
854 If you are on a machine that supports membership in multiple groups
855 simultaneously, gives a space separated list of groups you are in.
856 The first number is the one returned by getgid(), and the subsequent ones
857 by getgroups(), one of which may be the same as the first number.
858 (Mnemonic: parentheses are used to GROUP things.
859 The real gid is the group you LEFT, if you're running setgid.)
861 The effective gid of this process.
862 If you are on a machine that supports membership in multiple groups
863 simultaneously, gives a space separated list of groups you are in.
864 The first number is the one returned by getegid(), and the subsequent ones
865 by getgroups(), one of which may be the same as the first number.
866 (Mnemonic: parentheses are used to GROUP things.
867 The effective gid is the group that's RIGHT for you, if you're running setgid.)
869 Note: $<, $>, $( and $) can only be set on machines that support the
870 corresponding set[re][ug]id() routine.
871 $( and $) can only be swapped on machines supporting setregid().
873 The current set of characters after which a string may be broken to
874 fill continuation fields (starting with ^) in a format.
875 Default is "\ \en-", to break on whitespace or hyphens.
876 (Mnemonic: a \*(L"colon\*(R" in poetry is a part of a line.)
878 The array ARGV contains the command line arguments intended for the script.
879 Note that $#ARGV is the generally number of arguments minus one, since
880 $ARGV[0] is the first argument, NOT the command name.
881 See $0 for the command name.
883 The array INC contains the list of places to look for
886 evaluated by the \*(L"do EXPR\*(R" command.
887 It initially consists of the arguments to any
889 command line switches, followed
892 library, probably \*(L"/usr/local/lib/perl\*(R".
894 The associative array ENV contains your current environment.
895 Setting a value in ENV changes the environment for child processes.
897 The associative array SIG is used to set signal handlers for various signals.
902 sub handler { # 1st argument is signal name
904 print "Caught a SIG$sig\-\|\-shutting down\en";
909 $SIG{\'INT\'} = \'handler\';
910 $SIG{\'QUIT\'} = \'handler\';
912 $SIG{\'INT\'} = \'DEFAULT\'; # restore default action
913 $SIG{\'QUIT\'} = \'IGNORE\'; # ignore SIGQUIT
916 The SIG array only contains values for the signals actually set within
919 Perl provides a mechanism for alternate namespaces to protect packages from
920 stomping on each others variables.
921 By default, a perl script starts compiling into the package known as \*(L"main\*(R".
924 declaration, you can switch namespaces.
925 The scope of the package declaration is from the declaration itself to the end
926 of the enclosing block (the same scope as the local() operator).
927 Typically it would be the first declaration in a file to be included by
928 the \*(L"do FILE\*(R" operator.
929 You can switch into a package in more than one place; it merely influences
930 which symbol table is used by the compiler for the rest of that block.
931 You can refer to variables and filehandles in other packages by prefixing
932 the identifier with the package name and a single quote.
933 If the package name is null, the \*(L"main\*(R" package as assumed.
935 Only identifiers starting with letters are stored in the packages symbol
937 All other symbols are kept in package \*(L"main\*(R".
938 In addition, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC
939 and SIG are forced to be in package \*(L"main\*(R", even when used for
940 other purposes than their built-in one.
941 Note also that, if you have a package called \*(L"m\*(R", \*(L"s\*(R"
942 or \*(L"y\*(R", the you can't use the qualified form of an identifier since it
943 will be interpreted instead as a pattern match, a substitution
946 Eval'ed strings are compiled in the package in which the eval was compiled
948 (Assignments to $SIG{}, however, assume the signal handler specified is in the
950 Qualify the signal handler name if you wish to have a signal handler in
952 For an example, examine perldb.pl in the perl library.
953 It initially switches to the DB package so that the debugger doesn't interfere
954 with variables in the script you are trying to debug.
955 At various points, however, it temporarily switches back to the main package
956 to evaluate various expressions in the context of the main package.
958 The symbol table for a package happens to be stored in the associative array
959 of that name prepended with an underscore.
960 The value in each entry of the associative array is
961 what you are referring to when you use the *name notation.
962 In fact, the following have the same effect (in package main, anyway),
963 though the first is more
964 efficient because it does the symbol table lookups at compile time:
969 local($_main{'foo'}) = $_main{'bar'};
972 You can use this to print out all the variables in a package, for instance.
973 Here is dumpvar.pl from the perl library:
980 \& local(*stab) = eval("*_$package");
981 \& while (($key,$val) = each(%stab)) {
983 \& local(*entry) = $val;
984 \& if (defined $entry) {
985 \& print "\e$$key = '$entry'\en";
988 \& if (defined @entry) {
989 \& print "\e@$key = (\en";
990 \& foreach $num ($[ .. $#entry) {
991 \& print " $num\et'",$entry[$num],"'\en";
996 \& if ($key ne "_$package" && defined %entry) {
997 \& print "\e%$key = (\en";
998 \& foreach $key (sort keys(%entry)) {
999 \& print " $key\et'",$entry{$key},"'\en";
1008 Note that, even though the subroutine is compiled in package dumpvar, the
1009 name of the subroutine is qualified so that its name is inserted into package
1012 Each programmer will, of course, have his or her own preferences in regards
1013 to formatting, but there are some general guidelines that will make your
1014 programs easier to read.
1016 Just because you CAN do something a particular way doesn't mean that
1017 you SHOULD do it that way.
1019 is designed to give you several ways to do anything, so consider picking
1020 the most readable one.
1023 open(FOO,$foo) || die "Can't open $foo: $!";
1027 die "Can't open $foo: $!" unless open(FOO,$foo);
1029 because the second way hides the main point of the statement in a
1033 print "Starting analysis\en" if $verbose;
1037 $verbose && print "Starting analysis\en";
1039 since the main point isn't whether the user typed -v or not.
1041 Similarly, just because an operator lets you assume default arguments
1042 doesn't mean that you have to make use of the defaults.
1043 The defaults are there for lazy systems programmers writing one-shot
1045 If you want your program to be readable, consider supplying the argument.
1047 Along the same lines, just because you
1049 omit parentheses in many places doesn't mean that you ought to:
1052 return print reverse sort num values array;
1053 return print(reverse(sort num (values(%array))));
1056 When in doubt, parenthesize.
1057 At the very least it will let some poor schmuck bounce on the % key in vi.
1059 Don't go through silly contortions to exit a loop at the top or the
1062 provides the "last" operator so you can exit in the middle.
1063 Just outdent it a little to make it more visible:
1077 Don't be afraid to use loop labels\*(--they're there to enhance readability as
1078 well as to allow multi-level loop breaks.
1081 For portability, when using features that may not be implemented on every
1082 machine, test the construct in an eval to see if it fails.
1083 If you know what version or patchlevel a particular feature was implemented,
1084 you can test $] to see if it will be there.
1086 Choose mnemonic identifiers.
1094 switch, your script will be run under a debugging monitor.
1095 It will halt before the first executable statement and ask you for a
1098 Prints out a help message.
1101 Executes until it reaches the beginning of another statement.
1104 Executes until the next breakpoint is reached.
1108 Single step around subroutine call.
1109 .Ip "l min+incr" 12 4
1110 List incr+1 lines starting at min.
1111 If min is omitted, starts where last listing left off.
1112 If incr is omitted, previous value of incr is used.
1113 .Ip "l min-max" 12 4
1114 List lines in the indicated range.
1116 List just the indicated line.
1118 List incr+1 more lines after last printed line.
1119 .Ip "l subname" 12 4
1121 If it's a long subroutine it just lists the beginning.
1122 Use \*(L"l\*(R" to list more.
1124 List lines that have breakpoints or actions.
1126 Toggle trace mode on or off.
1129 If line is omitted, sets a breakpoint on the current line
1130 line that is about to be executed.
1131 Breakpoints may only be set on lines that begin an executable statement.
1132 .Ip "b subname" 12 4
1133 Set breakpoint at first executable line of subroutine.
1135 Lists the names of all subroutines.
1138 If line is omitted, deletes the breakpoint on the current line
1139 line that is about to be executed.
1141 Delete all breakpoints.
1143 Delete all line actions.
1144 .Ip "V package" 12 4
1145 List all variables in package.
1146 Default is main package.
1147 .Ip "a line command" 12 4
1148 Set an action for line.
1149 A multi-line command may be entered by backslashing the newlines.
1150 .Ip "< command" 12 4
1151 Set an action to happen before every debugger prompt.
1152 A multi-line command may be entered by backslashing the newlines.
1153 .Ip "> command" 12 4
1154 Set an action to happen after the prompt when you've just given a command
1155 to return to executing the script.
1156 A multi-line command may be entered by backslashing the newlines.
1158 Redo a debugging command.
1159 If number is omitted, redoes the previous command.
1160 .Ip "! -number" 12 4
1161 Redo the command that was that many commands ago.
1162 .Ip "H -number" 12 4
1163 Display last n commands.
1164 Only commands longer than one character are listed.
1165 If number is omitted, lists them all.
1169 Execute command as a perl statement.
1170 A missing semicolon will be supplied.
1172 Same as \*(L"print DB'OUT expr\*(R".
1173 The DB'OUT filehandle is opened to /dev/tty, regardless of where STDOUT
1174 may be redirected to.
1176 If you want to modify the debugger, copy perldb.pl from the perl library
1177 to your current directory and modify it as necessary.
1178 You can do some customization by setting up a .perldb file which contains
1179 initialization code.
1180 For instance, you could make aliases like these:
1183 $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
1184 $DB'alias{'stop'} = 's/^stop (at|in)/b/';
1186 's/^\e./p "\e$DB\e'sub(\e$DB\e'line):\et",\e$DB\e'line[\e$DB\e'line]/';
1189 .Sh "Setuid Scripts"
1191 is designed to make it easy to write secure setuid and setgid scripts.
1192 Unlike shells, which are based on multiple substitution passes on each line
1195 uses a more conventional evaluation scheme with fewer hidden \*(L"gotchas\*(R".
1196 Additionally, since the language has more built-in functionality, it
1197 has to rely less upon external (and possibly untrustworthy) programs to
1198 accomplish its purposes.
1200 In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
1201 insecure, but this kernel feature can be disabled.
1204 can emulate the setuid and setgid mechanism when it notices the otherwise
1205 useless setuid/gid bits on perl scripts.
1206 If the kernel feature isn't disabled,
1208 will complain loudly that your setuid script is insecure.
1209 You'll need to either disable the kernel setuid script feature, or put
1210 a C wrapper around the script.
1212 When perl is executing a setuid script, it takes special precautions to
1213 prevent you from falling into any obvious traps.
1214 (In some ways, a perl script is more secure than the corresponding
1216 Any command line argument, environment variable, or input is marked as
1217 \*(L"tainted\*(R", and may not be used, directly or indirectly, in any
1218 command that invokes a subshell, or in any command that modifies files,
1219 directories or processes.
1220 Any variable that is set within an expression that has previously referenced
1221 a tainted value also becomes tainted (even if it is logically impossible
1222 for the tainted value to influence the variable).
1227 $foo = shift; # $foo is tainted
1228 $bar = $foo,\'bar\'; # $bar is also tainted
1229 $xxx = <>; # Tainted
1230 $path = $ENV{\'PATH\'}; # Tainted, but see below
1231 $abc = \'abc\'; # Not tainted
1234 system "echo $foo"; # Insecure
1235 system "/bin/echo", $foo; # Secure (doesn't use sh)
1236 system "echo $bar"; # Insecure
1237 system "echo $abc"; # Insecure until PATH set
1240 $ENV{\'PATH\'} = \'/bin:/usr/bin\';
1241 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1243 $path = $ENV{\'PATH\'}; # Not tainted
1244 system "echo $abc"; # Is secure now!
1247 open(FOO,"$foo"); # OK
1248 open(FOO,">$foo"); # Not OK
1250 open(FOO,"echo $foo|"); # Not OK, but...
1251 open(FOO,"-|") || exec \'echo\', $foo; # OK
1253 $zzz = `echo $foo`; # Insecure, zzz tainted
1255 unlink $abc,$foo; # Insecure
1256 umask $foo; # Insecure
1259 exec "echo $foo"; # Insecure
1260 exec "echo", $foo; # Secure (doesn't use sh)
1261 exec "sh", \'-c\', $foo; # Considered secure, alas
1264 The taintedness is associated with each scalar value, so some elements
1265 of an array can be tainted, and others not.
1267 If you try to do something insecure, you will get a fatal error saying
1268 something like \*(L"Insecure dependency\*(R" or \*(L"Insecure PATH\*(R".
1269 Note that you can still write an insecure system call or exec,
1270 but only by explicitly doing something like the last example above.
1271 You can also bypass the tainting mechanism by referencing
1274 presumes that if you reference a substring using $1, $2, etc, you knew
1275 what you were doing when you wrote the pattern:
1278 $ARGV[0] =~ /^\-P(\ew+)$/;
1279 $printer = $1; # Not tainted
1282 This is fairly secure since \ew+ doesn't match shell metacharacters.
1283 Use of .+ would have been insecure, but
1285 doesn't check for that, so you must be careful with your patterns.
1286 This is the ONLY mechanism for untainting user supplied filenames if you
1287 want to do file operations on them (unless you make $> equal to $<).
1289 It's also possible to get into trouble with other operations that don't care
1290 whether they use tainted values.
1291 Make judicious use of the file tests in dealing with any user-supplied
1293 When possible, do opens and such after setting $> = $<.
1295 doesn't prevent you from opening tainted filenames for reading, so be
1296 careful what you print out.
1297 The tainting mechanism is intended to prevent stupid mistakes, not to remove
1298 the need for thought.
1301 uses PATH in executing subprocesses, and in finding the script if \-S
1303 HOME or LOGDIR are used if chdir has no argument.
1307 uses no environment variables, except to make them available
1308 to the script being executed, and to child processes.
1309 However, scripts running setuid would do well to execute the following lines
1310 before doing anything else, just to keep people honest:
1314 $ENV{\'PATH\'} = \'/bin:/usr/bin\'; # or whatever you need
1315 $ENV{\'SHELL\'} = \'/bin/sh\' if $ENV{\'SHELL\'} ne \'\';
1316 $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
1320 Larry Wall <lwall@jpl-devvax.Jpl.Nasa.Gov>
1322 /tmp/perl\-eXXXXXX temporary file for
1326 a2p awk to perl translator
1328 s2p sed to perl translator
1330 Compilation errors will tell you the line number of the error, with an
1331 indication of the next token or token type that was to be examined.
1332 (In the case of a script passed to
1338 is counted as one line.)
1340 Setuid scripts have additional constraints that can produce error messages
1341 such as \*(L"Insecure dependency\*(R".
1342 See the section on setuid scripts.
1346 users should take special note of the following:
1348 Semicolons are required after all simple statements in
1351 is not a statement delimiter.
1353 Curly brackets are required on ifs and whiles.
1355 Variables begin with $ or @ in
1358 Arrays index from 0 unless you set $[.
1359 Likewise string positions in substr() and index().
1361 You have to decide whether your array has numeric or string indices.
1363 Associative array values do not spring into existence upon mere reference.
1365 You have to decide whether you want to use string or numeric comparisons.
1367 Reading an input line does not split it for you. You get to split it yourself
1371 operator has different arguments.
1373 The current input line is normally in $_, not $0.
1374 It generally does not have the newline stripped.
1375 ($0 is the name of the program executed.)
1377 $<digit> does not refer to fields\*(--it refers to substrings matched by the last
1382 statement does not add field and record separators unless you set
1385 You must open your files before you print to them.
1387 The range operator is \*(L".\|.\*(R", not comma.
1388 (The comma operator works as in C.)
1390 The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
1391 (\*(L"~\*(R" is the one's complement operator, as in C.)
1393 The exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
1394 (\*(L"^\*(R" is the XOR operator, as in C.)
1396 The concatenation operator is \*(L".\*(R", not the null string.
1397 (Using the null string would render \*(L"/pat/ /pat/\*(R" unparsable,
1398 since the third slash would be interpreted as a division operator\*(--the
1399 tokener is in fact slightly context sensitive for operators like /, ?, and <.
1400 And in fact, . itself can be the beginning of a number.)
1408 The following variables work differently
1412 ARGC \h'|2.5i'$#ARGV
1414 FILENAME\h'|2.5i'$ARGV
1415 FNR \h'|2.5i'$. \- something
1416 FS \h'|2.5i'(whatever you like)
1417 NF \h'|2.5i'$#Fld, or some such
1422 RLENGTH \h'|2.5i'length($&)
1424 RSTART \h'|2.5i'length($\`)
1429 When in doubt, run the
1431 construct through a2p and see what it gives you.
1433 Cerebral C programmers should take note of the following:
1435 Curly brackets are required on ifs and whiles.
1437 You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
1448 There's no switch statement.
1450 Variables begin with $ or @ in
1453 Printf does not implement *.
1455 Comments begin with #, not /*.
1457 You can't take the address of anything.
1459 ARGV must be capitalized.
1461 The \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
1463 Signal handlers deal with signal names, not numbers.
1467 programmers should take note of the following:
1469 Backreferences in substitutions use $ rather than \e.
1471 The pattern matching metacharacters (, ), and | do not have backslashes in front.
1473 The range operator is .\|. rather than comma.
1475 Sharp shell programmers should take note of the following:
1477 The backtick operator does variable interpretation without regard to the
1478 presence of single quotes in the command.
1480 The backtick operator does no translation of the return value, unlike csh.
1482 Shells (especially csh) do several levels of substitution on each command line.
1484 does substitution only in certain constructs such as double quotes,
1485 backticks, angle brackets and search patterns.
1487 Shells interpret scripts a little bit at a time.
1489 compiles the whole program before executing it.
1491 The arguments are available via @ARGV, not $1, $2, etc.
1493 The environment is not automatically made available as variables.
1497 is at the mercy of your machine's definitions of various operations
1498 such as type casting, atof() and sprintf().
1500 If your stdio requires an seek or eof between reads and writes on a particular
1504 While none of the built-in data types have any arbitrary size limits (apart
1505 from memory size), there are still a few arbitrary limits:
1506 a given identifier may not be longer than 255 characters;
1507 sprintf is limited on many machines to 128 characters per field (unless the format
1508 specifier is exactly %s);
1509 and no component of your PATH may be longer than 255 if you use \-S.
1512 actually stands for Pathologically Eclectic Rubbish Lister, but don't tell