This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perl 3.0 patch #41 (combined patch)
[perl5.git] / perl.man.1
1 .rn '' }`
2 ''' $Header: perl_man.1,v 3.0.1.10 90/11/10 01:45:16 lwall Locked $
3 ''' 
4 ''' $Log:       perl.man.1,v $
5 ''' Revision 3.0.1.10  90/11/10  01:45:16  lwall
6 ''' patch38: random cleanup
7 ''' 
8 ''' Revision 3.0.1.9  90/10/20  02:14:24  lwall
9 ''' patch37: fixed various typos in man page
10 ''' 
11 ''' Revision 3.0.1.8  90/10/15  18:16:19  lwall
12 ''' patch29: added DATA filehandle to read stuff after __END__
13 ''' patch29: added cmp and <=>
14 ''' patch29: added -M, -A and -C
15 ''' 
16 ''' Revision 3.0.1.7  90/08/09  04:24:03  lwall
17 ''' patch19: added -x switch to extract script from input trash
18 ''' patch19: Added -c switch to do compilation only
19 ''' patch19: bare identifiers are now strings if no other interpretation possible
20 ''' patch19: -s now returns size of file
21 ''' patch19: Added __LINE__ and __FILE__ tokens
22 ''' patch19: Added __END__ token
23 ''' 
24 ''' Revision 3.0.1.6  90/08/03  11:14:44  lwall
25 ''' patch19: Intermediate diffs for Randal
26 ''' 
27 ''' Revision 3.0.1.5  90/03/27  16:14:37  lwall
28 ''' patch16: .. now works using magical string increment
29 ''' 
30 ''' Revision 3.0.1.4  90/03/12  16:44:33  lwall
31 ''' patch13: (LIST,) now legal
32 ''' patch13: improved LIST documentation
33 ''' patch13: example of if-elsif switch was wrong  
34 ''' 
35 ''' Revision 3.0.1.3  90/02/28  17:54:32  lwall
36 ''' patch9: @array in scalar context now returns length of array
37 ''' patch9: in manual, example of open and ?: was backwards
38 ''' 
39 ''' Revision 3.0.1.2  89/11/17  15:30:03  lwall
40 ''' patch5: fixed some manual typos and indent problems
41 ''' 
42 ''' Revision 3.0.1.1  89/11/11  04:41:22  lwall
43 ''' patch2: explained about sh and ${1+"$@"}
44 ''' patch2: documented that space must separate word and '' string
45 ''' 
46 ''' Revision 3.0  89/10/18  15:21:29  lwall
47 ''' 3.0 baseline
48 ''' 
49 ''' 
50 .de Sh
51 .br
52 .ne 5
53 .PP
54 \fB\\$1\fR
55 .PP
56 ..
57 .de Sp
58 .if t .sp .5v
59 .if n .sp
60 ..
61 .de Ip
62 .br
63 .ie \\n(.$>=3 .ne \\$3
64 .el .ne 3
65 .IP "\\$1" \\$2
66 ..
67 '''
68 '''     Set up \*(-- to give an unbreakable dash;
69 '''     string Tr holds user defined translation string.
70 '''     Bell System Logo is used as a dummy character.
71 '''
72 .tr \(*W-|\(bv\*(Tr
73 .ie n \{\
74 .ds -- \(*W-
75 .if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
76 .if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
77 .ds L" ""
78 .ds R" ""
79 .ds L' '
80 .ds R' '
81 'br\}
82 .el\{\
83 .ds -- \(em\|
84 .tr \*(Tr
85 .ds L" ``
86 .ds R" ''
87 .ds L' `
88 .ds R' '
89 'br\}
90 .TH PERL 1 "\*(RP"
91 .UC
92 .SH NAME
93 perl \- Practical Extraction and Report Language
94 .SH SYNOPSIS
95 .B perl
96 [options] filename args
97 .SH DESCRIPTION
98 .I Perl
99 is an interpreted language optimized for scanning arbitrary text files,
100 extracting information from those text files, and printing reports based
101 on that information.
102 It's also a good language for many system management tasks.
103 The language is intended to be practical (easy to use, efficient, complete)
104 rather than beautiful (tiny, elegant, minimal).
105 It combines (in the author's opinion, anyway) some of the best features of C,
106 \fIsed\fR, \fIawk\fR, and \fIsh\fR,
107 so people familiar with those languages should have little difficulty with it.
108 (Language historians will also note some vestiges of \fIcsh\fR, Pascal, and
109 even BASIC-PLUS.)
110 Expression syntax corresponds quite closely to C expression syntax.
111 Unlike most Unix utilities,
112 .I perl
113 does not arbitrarily limit the size of your data\*(--if you've got
114 the memory,
115 .I perl
116 can slurp in your whole file as a single string.
117 Recursion is of unlimited depth.
118 And the hash tables used by associative arrays grow as necessary to prevent
119 degraded performance.
120 .I Perl
121 uses sophisticated pattern matching techniques to scan large amounts of
122 data very quickly.
123 Although optimized for scanning text,
124 .I perl
125 can also deal with binary data, and can make dbm files look like associative
126 arrays (where dbm is available).
127 Setuid
128 .I perl
129 scripts are safer than C programs
130 through a dataflow tracing mechanism which prevents many stupid security holes.
131 If you have a problem that would ordinarily use \fIsed\fR
132 or \fIawk\fR or \fIsh\fR, but it
133 exceeds their capabilities or must run a little faster,
134 and you don't want to write the silly thing in C, then
135 .I perl
136 may be for you.
137 There are also translators to turn your
138 .I sed
139 and
140 .I awk
141 scripts into
142 .I perl
143 scripts.
144 OK, enough hype.
145 .PP
146 Upon startup,
147 .I perl
148 looks for your script in one of the following places:
149 .Ip 1. 4 2
150 Specified line by line via
151 .B \-e
152 switches on the command line.
153 .Ip 2. 4 2
154 Contained in the file specified by the first filename on the command line.
155 (Note that systems supporting the #! notation invoke interpreters this way.)
156 .Ip 3. 4 2
157 Passed in implicitly via standard input.
158 This only works if there are no filename arguments\*(--to pass
159 arguments to a
160 .I stdin
161 script you must explicitly specify a \- for the script name.
162 .PP
163 After locating your script,
164 .I perl
165 compiles it to an internal form.
166 If the script is syntactically correct, it is executed.
167 .Sh "Options"
168 Note: on first reading this section may not make much sense to you.  It's here
169 at the front for easy reference.
170 .PP
171 A single-character option may be combined with the following option, if any.
172 This is particularly useful when invoking a script using the #! construct which
173 only allows one argument.  Example:
174 .nf
175
176 .ne 2
177         #!/usr/bin/perl \-spi.bak       # same as \-s \-p \-i.bak
178         .\|.\|.
179
180 .fi
181 Options include:
182 .TP 5
183 .B \-a
184 turns on autosplit mode when used with a
185 .B \-n
186 or
187 .BR \-p .
188 An implicit split command to the @F array
189 is done as the first thing inside the implicit while loop produced by
190 the
191 .B \-n
192 or
193 .BR \-p .
194 .nf
195
196         perl \-ane \'print pop(@F), "\en";\'
197
198 is equivalent to
199
200         while (<>) {
201                 @F = split(\' \');
202                 print pop(@F), "\en";
203         }
204
205 .fi
206 .TP 5
207 .B \-c
208 causes
209 .I perl
210 to check the syntax of the script and then exit without executing it.
211 .TP 5
212 .BI \-d
213 runs the script under the perl debugger.
214 See the section on Debugging.
215 .TP 5
216 .BI \-D number
217 sets debugging flags.
218 To watch how it executes your script, use
219 .BR \-D14 .
220 (This only works if debugging is compiled into your
221 .IR perl .)
222 Another nice value is \-D1024, which lists your compiled syntax tree.
223 And \-D512 displays compiled regular expressions.
224 .TP 5
225 .BI \-e " commandline"
226 may be used to enter one line of script.
227 Multiple
228 .B \-e
229 commands may be given to build up a multi-line script.
230 If
231 .B \-e
232 is given,
233 .I perl
234 will not look for a script filename in the argument list.
235 .TP 5
236 .BI \-i extension
237 specifies that files processed by the <> construct are to be edited
238 in-place.
239 It does this by renaming the input file, opening the output file by the
240 same name, and selecting that output file as the default for print statements.
241 The extension, if supplied, is added to the name of the
242 old file to make a backup copy.
243 If no extension is supplied, no backup is made.
244 Saying \*(L"perl \-p \-i.bak \-e "s/foo/bar/;" .\|.\|. \*(R" is the same as using
245 the script:
246 .nf
247
248 .ne 2
249         #!/usr/bin/perl \-pi.bak
250         s/foo/bar/;
251
252 which is equivalent to
253
254 .ne 14
255         #!/usr/bin/perl
256         while (<>) {
257                 if ($ARGV ne $oldargv) {
258                         rename($ARGV, $ARGV . \'.bak\');
259                         open(ARGVOUT, ">$ARGV");
260                         select(ARGVOUT);
261                         $oldargv = $ARGV;
262                 }
263                 s/foo/bar/;
264         }
265         continue {
266             print;      # this prints to original filename
267         }
268         select(STDOUT);
269
270 .fi
271 except that the
272 .B \-i
273 form doesn't need to compare $ARGV to $oldargv to know when
274 the filename has changed.
275 It does, however, use ARGVOUT for the selected filehandle.
276 Note that
277 .I STDOUT
278 is restored as the default output filehandle after the loop.
279 .Sp
280 You can use eof to locate the end of each input file, in case you want
281 to append to each file, or reset line numbering (see example under eof).
282 .TP 5
283 .BI \-I directory
284 may be used in conjunction with
285 .B \-P
286 to tell the C preprocessor where to look for include files.
287 By default /usr/include and /usr/lib/perl are searched.
288 .TP 5
289 .B \-n
290 causes
291 .I perl
292 to assume the following loop around your script, which makes it iterate
293 over filename arguments somewhat like \*(L"sed \-n\*(R" or \fIawk\fR:
294 .nf
295
296 .ne 3
297         while (<>) {
298                 .\|.\|.         # your script goes here
299         }
300
301 .fi
302 Note that the lines are not printed by default.
303 See
304 .B \-p
305 to have lines printed.
306 Here is an efficient way to delete all files older than a week:
307 .nf
308
309         find . \-mtime +7 \-print | perl \-ne \'chop;unlink;\'
310
311 .fi
312 This is faster than using the \-exec switch of find because you don't have to
313 start a process on every filename found.
314 .TP 5
315 .B \-p
316 causes
317 .I perl
318 to assume the following loop around your script, which makes it iterate
319 over filename arguments somewhat like \fIsed\fR:
320 .nf
321
322 .ne 5
323         while (<>) {
324                 .\|.\|.         # your script goes here
325         } continue {
326                 print;
327         }
328
329 .fi
330 Note that the lines are printed automatically.
331 To suppress printing use the
332 .B \-n
333 switch.
334 A
335 .B \-p
336 overrides a
337 .B \-n
338 switch.
339 .TP 5
340 .B \-P
341 causes your script to be run through the C preprocessor before
342 compilation by
343 .IR perl .
344 (Since both comments and cpp directives begin with the # character,
345 you should avoid starting comments with any words recognized
346 by the C preprocessor such as \*(L"if\*(R", \*(L"else\*(R" or \*(L"define\*(R".)
347 .TP 5
348 .B \-s
349 enables some rudimentary switch parsing for switches on the command line
350 after the script name but before any filename arguments (or before a \-\|\-).
351 Any switch found there is removed from @ARGV and sets the corresponding variable in the
352 .I perl
353 script.
354 The following script prints \*(L"true\*(R" if and only if the script is
355 invoked with a \-xyz switch.
356 .nf
357
358 .ne 2
359         #!/usr/bin/perl \-s
360         if ($xyz) { print "true\en"; }
361
362 .fi
363 .TP 5
364 .B \-S
365 makes
366 .I perl
367 use the PATH environment variable to search for the script
368 (unless the name of the script starts with a slash).
369 Typically this is used to emulate #! startup on machines that don't
370 support #!, in the following manner:
371 .nf
372
373         #!/usr/bin/perl
374         eval "exec /usr/bin/perl \-S $0 $*"
375                 if $running_under_some_shell;
376
377 .fi
378 The system ignores the first line and feeds the script to /bin/sh,
379 which proceeds to try to execute the
380 .I perl
381 script as a shell script.
382 The shell executes the second line as a normal shell command, and thus
383 starts up the
384 .I perl
385 interpreter.
386 On some systems $0 doesn't always contain the full pathname,
387 so the
388 .B \-S
389 tells
390 .I perl
391 to search for the script if necessary.
392 After
393 .I perl
394 locates the script, it parses the lines and ignores them because
395 the variable $running_under_some_shell is never true.
396 A better construct than $* would be ${1+"$@"}, which handles embedded spaces
397 and such in the filenames, but doesn't work if the script is being interpreted
398 by csh.
399 In order to start up sh rather than csh, some systems may have to replace the
400 #! line with a line containing just
401 a colon, which will be politely ignored by perl.
402 Other systems can't control that, and need a totally devious construct that
403 will work under any of csh, sh or perl, such as the following:
404 .nf
405
406 .ne 3
407         eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
408         & eval 'exec /usr/bin/perl -S $0 $argv:q'
409                 if 0;
410
411 .fi
412 .TP 5
413 .B \-u
414 causes
415 .I perl
416 to dump core after compiling your script.
417 You can then take this core dump and turn it into an executable file
418 by using the undump program (not supplied).
419 This speeds startup at the expense of some disk space (which you can
420 minimize by stripping the executable).
421 (Still, a "hello world" executable comes out to about 200K on my machine.)
422 If you are going to run your executable as a set-id program then you
423 should probably compile it using taintperl rather than normal perl.
424 If you want to execute a portion of your script before dumping, use the
425 dump operator instead.
426 Note: availability of undump is platform specific and may not be available
427 for a specific port of perl.
428 .TP 5
429 .B \-U
430 allows
431 .I perl
432 to do unsafe operations.
433 Currently the only \*(L"unsafe\*(R" operation is the unlinking of directories while
434 running as superuser.
435 .TP 5
436 .B \-v
437 prints the version and patchlevel of your
438 .I perl
439 executable.
440 .TP 5
441 .B \-w
442 prints warnings about identifiers that are mentioned only once, and scalar
443 variables that are used before being set.
444 Also warns about redefined subroutines, and references to undefined
445 filehandles or filehandles opened readonly that you are attempting to
446 write on.
447 Also warns you if you use == on values that don't look like numbers, and if
448 your subroutines recurse more than 100 deep.
449 .TP 5
450 .BI \-x directory
451 tells
452 .I perl
453 that the script is embedded in a message.
454 Leading garbage will be discarded until the first line that starts
455 with #! and contains the string "perl".
456 Any meaningful switches on that line will be applied (but only one
457 group of switches, as with normal #! processing).
458 If a directory name is specified, Perl will switch to that directory
459 before running the script.
460 The
461 .B \-x
462 switch only controls the the disposal of leading garbage.
463 The script must be terminated with __END__ if there is trailing garbage
464 to be ignored (the script can process any or all of the trailing garbage
465 via the DATA filehandle if desired).
466 .Sh "Data Types and Objects"
467 .PP
468 .I Perl
469 has three data types: scalars, arrays of scalars, and
470 associative arrays of scalars.
471 Normal arrays are indexed by number, and associative arrays by string.
472 .PP
473 The interpretation of operations and values in perl sometimes
474 depends on the requirements
475 of the context around the operation or value.
476 There are three major contexts: string, numeric and array.
477 Certain operations return array values
478 in contexts wanting an array, and scalar values otherwise.
479 (If this is true of an operation it will be mentioned in the documentation
480 for that operation.)
481 Operations which return scalars don't care whether the context is looking
482 for a string or a number, but
483 scalar variables and values are interpreted as strings or numbers
484 as appropriate to the context.
485 A scalar is interpreted as TRUE in the boolean sense if it is not the null
486 string or 0.
487 Booleans returned by operators are 1 for true and 0 or \'\' (the null
488 string) for false.
489 .PP
490 There are actually two varieties of null string: defined and undefined.
491 Undefined null strings are returned when there is no real value for something,
492 such as when there was an error, or at end of file, or when you refer
493 to an uninitialized variable or element of an array.
494 An undefined null string may become defined the first time you access it, but
495 prior to that you can use the defined() operator to determine whether the
496 value is defined or not.
497 .PP
498 References to scalar variables always begin with \*(L'$\*(R', even when referring
499 to a scalar that is part of an array.
500 Thus:
501 .nf
502
503 .ne 3
504     $days       \h'|2i'# a simple scalar variable
505     $days[28]   \h'|2i'# 29th element of array @days
506     $days{\'Feb\'}\h'|2i'# one value from an associative array
507     $#days      \h'|2i'# last index of array @days
508
509 but entire arrays or array slices are denoted by \*(L'@\*(R':
510
511     @days       \h'|2i'# ($days[0], $days[1],\|.\|.\|. $days[n])
512     @days[3,4,5]\h'|2i'# same as @days[3.\|.5]
513     @days{'a','c'}\h'|2i'# same as ($days{'a'},$days{'c'})
514
515 and entire associative arrays are denoted by \*(L'%\*(R':
516
517     %days       \h'|2i'# (key1, val1, key2, val2 .\|.\|.)
518 .fi
519 .PP
520 Any of these eight constructs may serve as an lvalue,
521 that is, may be assigned to.
522 (It also turns out that an assignment is itself an lvalue in
523 certain contexts\*(--see examples under s, tr and chop.)
524 Assignment to a scalar evaluates the righthand side in a scalar context,
525 while assignment to an array or array slice evaluates the righthand side
526 in an array context.
527 .PP
528 You may find the length of array @days by evaluating
529 \*(L"$#days\*(R", as in
530 .IR csh .
531 (Actually, it's not the length of the array, it's the subscript of the last element, since there is (ordinarily) a 0th element.)
532 Assigning to $#days changes the length of the array.
533 Shortening an array by this method does not actually destroy any values.
534 Lengthening an array that was previously shortened recovers the values that
535 were in those elements.
536 You can also gain some measure of efficiency by preextending an array that
537 is going to get big.
538 (You can also extend an array by assigning to an element that is off the
539 end of the array.
540 This differs from assigning to $#whatever in that intervening values
541 are set to null rather than recovered.)
542 You can truncate an array down to nothing by assigning the null list () to
543 it.
544 The following are exactly equivalent
545 .nf
546
547         @whatever = ();
548         $#whatever = $[ \- 1;
549
550 .fi
551 .PP
552 If you evaluate an array in a scalar context, it returns the length of
553 the array.
554 The following is always true:
555 .nf
556
557         @whatever == $#whatever \- $[ + 1;
558
559 .fi
560 .PP
561 Multi-dimensional arrays are not directly supported, but see the discussion
562 of the $; variable later for a means of emulating multiple subscripts with
563 an associative array.
564 You could also write a subroutine to turn multiple subscripts into a single
565 subscript.
566 .PP
567 Every data type has its own namespace.
568 You can, without fear of conflict, use the same name for a scalar variable,
569 an array, an associative array, a filehandle, a subroutine name, and/or
570 a label.
571 Since variable and array references always start with \*(L'$\*(R', \*(L'@\*(R',
572 or \*(L'%\*(R', the \*(L"reserved\*(R" words aren't in fact reserved
573 with respect to variable names.
574 (They ARE reserved with respect to labels and filehandles, however, which
575 don't have an initial special character.
576 Hint: you could say open(LOG,\'logfile\') rather than open(log,\'logfile\').
577 Using uppercase filehandles also improves readability and protects you
578 from conflict with future reserved words.)
579 Case IS significant\*(--\*(L"FOO\*(R", \*(L"Foo\*(R" and \*(L"foo\*(R" are all
580 different names.
581 Names which start with a letter may also contain digits and underscores.
582 Names which do not start with a letter are limited to one character,
583 e.g. \*(L"$%\*(R" or \*(L"$$\*(R".
584 (Most of the one character names have a predefined significance to
585 .IR perl .
586 More later.)
587 .PP
588 Numeric literals are specified in any of the usual floating point or
589 integer formats:
590 .nf
591
592 .ne 5
593     12345
594     12345.67
595     .23E-10
596     0xffff      # hex
597     0377        # octal
598
599 .fi
600 String literals are delimited by either single or double quotes.
601 They work much like shell quotes:
602 double-quoted string literals are subject to backslash and variable
603 substitution; single-quoted strings are not (except for \e\' and \e\e).
604 The usual backslash rules apply for making characters such as newline, tab, etc.
605 You can also embed newlines directly in your strings, i.e. they can end on
606 a different line than they begin.
607 This is nice, but if you forget your trailing quote, the error will not be
608 reported until
609 .I perl
610 finds another line containing the quote character, which
611 may be much further on in the script.
612 Variable substitution inside strings is limited to scalar variables, normal
613 array values, and array slices.
614 (In other words, identifiers beginning with $ or @, followed by an optional
615 bracketed expression as a subscript.)
616 The following code segment prints out \*(L"The price is $100.\*(R"
617 .nf
618
619 .ne 2
620     $Price = \'$100\';\h'|3.5i'# not interpreted
621     print "The price is $Price.\e\|n";\h'|3.5i'# interpreted
622
623 .fi
624 Note that you can put curly brackets around the identifier to delimit it
625 from following alphanumerics.
626 Also note that a single quoted string must be separated from a preceding
627 word by a space, since single quote is a valid character in an identifier
628 (see Packages).
629 .PP
630 Two special literals are __LINE__ and __FILE__, which represent the current
631 line number and filename at that point in your program.
632 They may only be used as separate tokens; they will not be interpolated
633 into strings.
634 In addition, the token __END__ may be used to indicate the logical end of the
635 script before the actual end of file.
636 Any following text is ignored (but may be read via the DATA filehandle).
637 The two control characters ^D and ^Z are synonyms for __END__.
638 .PP
639 A word that doesn't have any other interpretation in the grammar will be
640 treated as if it had single quotes around it.
641 For this purpose, a word consists only of alphanumeric characters and underline,
642 and must start with an alphabetic character.
643 As with filehandles and labels, a bare word that consists entirely of
644 lowercase letters risks conflict with future reserved words, and if you
645 use the
646 .B \-w
647 switch, Perl will warn you about any such words.
648 .PP
649 Array values are interpolated into double-quoted strings by joining all the
650 elements of the array with the delimiter specified in the $" variable,
651 space by default.
652 (Since in versions of perl prior to 3.0 the @ character was not a metacharacter
653 in double-quoted strings, the interpolation of @array, $array[EXPR],
654 @array[LIST], $array{EXPR}, or @array{LIST} only happens if array is
655 referenced elsewhere in the program or is predefined.)
656 The following are equivalent:
657 .nf
658
659 .ne 4
660         $temp = join($",@ARGV);
661         system "echo $temp";
662
663         system "echo @ARGV";
664
665 .fi
666 Within search patterns (which also undergo double-quotish substitution)
667 there is a bad ambiguity:  Is /$foo[bar]/ to be
668 interpreted as /${foo}[bar]/ (where [bar] is a character class for the
669 regular expression) or as /${foo[bar]}/ (where [bar] is the subscript to
670 array @foo)?
671 If @foo doesn't otherwise exist, then it's obviously a character class.
672 If @foo exists, perl takes a good guess about [bar], and is almost always right.
673 If it does guess wrong, or if you're just plain paranoid,
674 you can force the correct interpretation with curly brackets as above.
675 .PP
676 A line-oriented form of quoting is based on the shell here-is syntax.
677 Following a << you specify a string to terminate the quoted material, and all lines
678 following the current line down to the terminating string are the value
679 of the item.
680 The terminating string may be either an identifier (a word), or some
681 quoted text.
682 If quoted, the type of quotes you use determines the treatment of the text,
683 just as in regular quoting.
684 An unquoted identifier works like double quotes.
685 There must be no space between the << and the identifier.
686 (If you put a space it will be treated as a null identifier, which is
687 valid, and matches the first blank line\*(--see Merry Christmas example below.)
688 The terminating string must appear by itself (unquoted and with no surrounding
689 whitespace) on the terminating line.
690 .nf
691
692         print <<EOF;            # same as above
693 The price is $Price.
694 EOF
695
696         print <<"EOF";          # same as above
697 The price is $Price.
698 EOF
699
700         print << x 10;          # null identifier is delimiter
701 Merry Christmas!
702
703         print <<`EOC`;          # execute commands
704 echo hi there
705 echo lo there
706 EOC
707
708         print <<foo, <<bar;     # you can stack them
709 I said foo.
710 foo
711 I said bar.
712 bar
713
714 .fi
715 Array literals are denoted by separating individual values by commas, and
716 enclosing the list in parentheses:
717 .nf
718
719         (LIST)
720
721 .fi
722 In a context not requiring an array value, the value of the array literal
723 is the value of the final element, as in the C comma operator.
724 For example,
725 .nf
726
727 .ne 4
728     @foo = (\'cc\', \'\-E\', $bar);
729
730 assigns the entire array value to array foo, but
731
732     $foo = (\'cc\', \'\-E\', $bar);
733
734 .fi
735 assigns the value of variable bar to variable foo.
736 Note that the value of an actual array in a scalar context is the length
737 of the array; the following assigns to $foo the value 3:
738 .nf
739
740 .ne 2
741     @foo = (\'cc\', \'\-E\', $bar);
742     $foo = @foo;                # $foo gets 3
743
744 .fi
745 You may have an optional comma before the closing parenthesis of an
746 array literal, so that you can say:
747 .nf
748
749     @foo = (
750         1,
751         2,
752         3,
753     );
754
755 .fi
756 When a LIST is evaluated, each element of the list is evaluated in
757 an array context, and the resulting array value is interpolated into LIST
758 just as if each individual element were a member of LIST.  Thus arrays
759 lose their identity in a LIST\*(--the list
760
761         (@foo,@bar,&SomeSub)
762
763 contains all the elements of @foo followed by all the elements of @bar,
764 followed by all the elements returned by the subroutine named SomeSub.
765 .PP
766 A list value may also be subscripted like a normal array.
767 Examples:
768 .nf
769
770         $time = (stat($file))[8];       # stat returns array value
771         $digit = ('a','b','c','d','e','f')[$digit-10];
772         return (pop(@foo),pop(@foo))[0];
773
774 .fi
775 .PP
776 Array lists may be assigned to if and only if each element of the list
777 is an lvalue:
778 .nf
779
780     ($a, $b, $c) = (1, 2, 3);
781
782     ($map{\'red\'}, $map{\'blue\'}, $map{\'green\'}) = (0x00f, 0x0f0, 0xf00);
783
784 The final element may be an array or an associative array:
785
786     ($a, $b, @rest) = split;
787     local($a, $b, %rest) = @_;
788
789 .fi
790 You can actually put an array anywhere in the list, but the first array
791 in the list will soak up all the values, and anything after it will get
792 a null value.
793 This may be useful in a local().
794 .PP
795 An associative array literal contains pairs of values to be interpreted
796 as a key and a value:
797 .nf
798
799 .ne 2
800     # same as map assignment above
801     %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
802
803 .fi
804 Array assignment in a scalar context returns the number of elements
805 produced by the expression on the right side of the assignment:
806 .nf
807
808         $x = (($foo,$bar) = (3,2,1));   # set $x to 3, not 2
809
810 .fi
811 .PP
812 There are several other pseudo-literals that you should know about.
813 If a string is enclosed by backticks (grave accents), it first undergoes
814 variable substitution just like a double quoted string.
815 It is then interpreted as a command, and the output of that command
816 is the value of the pseudo-literal, like in a shell.
817 In a scalar context, a single string consisting of all the output is
818 returned.
819 In an array context, an array of values is returned, one for each line
820 of output.
821 (You can set $/ to use a different line terminator.)
822 The command is executed each time the pseudo-literal is evaluated.
823 The status value of the command is returned in $? (see Predefined Names
824 for the interpretation of $?).
825 Unlike in \f2csh\f1, no translation is done on the return
826 data\*(--newlines remain newlines.
827 Unlike in any of the shells, single quotes do not hide variable names
828 in the command from interpretation.
829 To pass a $ through to the shell you need to hide it with a backslash.
830 .PP
831 Evaluating a filehandle in angle brackets yields the next line
832 from that file (newline included, so it's never false until EOF, at
833 which time an undefined value is returned).
834 Ordinarily you must assign that value to a variable,
835 but there is one situation where an automatic assignment happens.
836 If (and only if) the input symbol is the only thing inside the conditional of a
837 .I while
838 loop, the value is
839 automatically assigned to the variable \*(L"$_\*(R".
840 (This may seem like an odd thing to you, but you'll use the construct
841 in almost every
842 .I perl
843 script you write.)
844 Anyway, the following lines are equivalent to each other:
845 .nf
846
847 .ne 5
848     while ($_ = <STDIN>) { print; }
849     while (<STDIN>) { print; }
850     for (\|;\|<STDIN>;\|) { print; }
851     print while $_ = <STDIN>;
852     print while <STDIN>;
853
854 .fi
855 The filehandles
856 .IR STDIN ,
857 .I STDOUT
858 and
859 .I STDERR
860 are predefined.
861 (The filehandles
862 .IR stdin ,
863 .I stdout
864 and
865 .I stderr
866 will also work except in packages, where they would be interpreted as
867 local identifiers rather than global.)
868 Additional filehandles may be created with the
869 .I open
870 function.
871 .PP
872 If a <FILEHANDLE> is used in a context that is looking for an array, an array
873 consisting of all the input lines is returned, one line per array element.
874 It's easy to make a LARGE data space this way, so use with care.
875 .PP
876 The null filehandle <> is special and can be used to emulate the behavior of
877 \fIsed\fR and \fIawk\fR.
878 Input from <> comes either from standard input, or from each file listed on
879 the command line.
880 Here's how it works: the first time <> is evaluated, the ARGV array is checked,
881 and if it is null, $ARGV[0] is set to \'-\', which when opened gives you standard
882 input.
883 The ARGV array is then processed as a list of filenames.
884 The loop
885 .nf
886
887 .ne 3
888         while (<>) {
889                 .\|.\|.                 # code for each line
890         }
891
892 .ne 10
893 is equivalent to
894
895         unshift(@ARGV, \'\-\') \|if \|$#ARGV < $[;
896         while ($ARGV = shift) {
897                 open(ARGV, $ARGV);
898                 while (<ARGV>) {
899                         .\|.\|.         # code for each line
900                 }
901         }
902
903 .fi
904 except that it isn't as cumbersome to say.
905 It really does shift array ARGV and put the current filename into
906 variable ARGV.
907 It also uses filehandle ARGV internally.
908 You can modify @ARGV before the first <> as long as you leave the first
909 filename at the beginning of the array.
910 Line numbers ($.) continue as if the input was one big happy file.
911 (But see example under eof for how to reset line numbers on each file.)
912 .PP
913 .ne 5
914 If you want to set @ARGV to your own list of files, go right ahead.
915 If you want to pass switches into your script, you can
916 put a loop on the front like this:
917 .nf
918
919 .ne 10
920         while ($_ = $ARGV[0], /\|^\-/\|) {
921                 shift;
922             last if /\|^\-\|\-$\|/\|;
923                 /\|^\-D\|(.*\|)/ \|&& \|($debug = $1);
924                 /\|^\-v\|/ \|&& \|$verbose++;
925                 .\|.\|.         # other switches
926         }
927         while (<>) {
928                 .\|.\|.         # code for each line
929         }
930
931 .fi
932 The <> symbol will return FALSE only once.
933 If you call it again after this it will assume you are processing another
934 @ARGV list, and if you haven't set @ARGV, will input from
935 .IR STDIN .
936 .PP
937 If the string inside the angle brackets is a reference to a scalar variable
938 (e.g. <$foo>),
939 then that variable contains the name of the filehandle to input from.
940 .PP
941 If the string inside angle brackets is not a filehandle, it is interpreted
942 as a filename pattern to be globbed, and either an array of filenames or the
943 next filename in the list is returned, depending on context.
944 One level of $ interpretation is done first, but you can't say <$foo>
945 because that's an indirect filehandle as explained in the previous
946 paragraph.
947 You could insert curly brackets to force interpretation as a
948 filename glob: <${foo}>.
949 Example:
950 .nf
951
952 .ne 3
953         while (<*.c>) {
954                 chmod 0644, $_;
955         }
956
957 is equivalent to
958
959 .ne 5
960         open(foo, "echo *.c | tr \-s \' \et\er\ef\' \'\e\e012\e\e012\e\e012\e\e012\'|");
961         while (<foo>) {
962                 chop;
963                 chmod 0644, $_;
964         }
965
966 .fi
967 In fact, it's currently implemented that way.
968 (Which means it will not work on filenames with spaces in them unless
969 you have /bin/csh on your machine.)
970 Of course, the shortest way to do the above is:
971 .nf
972
973         chmod 0644, <*.c>;
974
975 .fi
976 .Sh "Syntax"
977 .PP
978 A
979 .I perl
980 script consists of a sequence of declarations and commands.
981 The only things that need to be declared in
982 .I perl
983 are report formats and subroutines.
984 See the sections below for more information on those declarations.
985 All uninitialized user-created objects are assumed to
986 start with a null or 0 value until they
987 are defined by some explicit operation such as assignment.
988 The sequence of commands is executed just once, unlike in
989 .I sed
990 and
991 .I awk
992 scripts, where the sequence of commands is executed for each input line.
993 While this means that you must explicitly loop over the lines of your input file
994 (or files), it also means you have much more control over which files and which
995 lines you look at.
996 (Actually, I'm lying\*(--it is possible to do an implicit loop with either the
997 .B \-n
998 or
999 .B \-p
1000 switch.)
1001 .PP
1002 A declaration can be put anywhere a command can, but has no effect on the
1003 execution of the primary sequence of commands\(*--declarations all take effect
1004 at compile time.
1005 Typically all the declarations are put at the beginning or the end of the script.
1006 .PP
1007 .I Perl
1008 is, for the most part, a free-form language.
1009 (The only exception to this is format declarations, for fairly obvious reasons.)
1010 Comments are indicated by the # character, and extend to the end of the line.
1011 If you attempt to use /* */ C comments, it will be interpreted either as
1012 division or pattern matching, depending on the context.
1013 So don't do that.
1014 .Sh "Compound statements"
1015 In
1016 .IR perl ,
1017 a sequence of commands may be treated as one command by enclosing it
1018 in curly brackets.
1019 We will call this a BLOCK.
1020 .PP
1021 The following compound commands may be used to control flow:
1022 .nf
1023
1024 .ne 4
1025         if (EXPR) BLOCK
1026         if (EXPR) BLOCK else BLOCK
1027         if (EXPR) BLOCK elsif (EXPR) BLOCK .\|.\|. else BLOCK
1028         LABEL while (EXPR) BLOCK
1029         LABEL while (EXPR) BLOCK continue BLOCK
1030         LABEL for (EXPR; EXPR; EXPR) BLOCK
1031         LABEL foreach VAR (ARRAY) BLOCK
1032         LABEL BLOCK continue BLOCK
1033
1034 .fi
1035 Note that, unlike C and Pascal, these are defined in terms of BLOCKs, not
1036 statements.
1037 This means that the curly brackets are \fIrequired\fR\*(--no dangling statements allowed.
1038 If you want to write conditionals without curly brackets there are several
1039 other ways to do it.
1040 The following all do the same thing:
1041 .nf
1042
1043 .ne 5
1044         if (!open(foo)) { die "Can't open $foo: $!"; }
1045         die "Can't open $foo: $!" unless open(foo);
1046         open(foo) || die "Can't open $foo: $!"; # foo or bust!
1047         open(foo) ? \'hi mom\' : die "Can't open $foo: $!";
1048                                 # a bit exotic, that last one
1049
1050 .fi
1051 .PP
1052 The
1053 .I if
1054 statement is straightforward.
1055 Since BLOCKs are always bounded by curly brackets, there is never any
1056 ambiguity about which
1057 .I if
1058 an
1059 .I else
1060 goes with.
1061 If you use
1062 .I unless
1063 in place of
1064 .IR if ,
1065 the sense of the test is reversed.
1066 .PP
1067 The
1068 .I while
1069 statement executes the block as long as the expression is true
1070 (does not evaluate to the null string or 0).
1071 The LABEL is optional, and if present, consists of an identifier followed by
1072 a colon.
1073 The LABEL identifies the loop for the loop control statements
1074 .IR next ,
1075 .IR last ,
1076 and
1077 .I redo
1078 (see below).
1079 If there is a
1080 .I continue
1081 BLOCK, it is always executed just before
1082 the conditional is about to be evaluated again, similarly to the third part
1083 of a
1084 .I for
1085 loop in C.
1086 Thus it can be used to increment a loop variable, even when the loop has
1087 been continued via the
1088 .I next
1089 statement (similar to the C \*(L"continue\*(R" statement).
1090 .PP
1091 If the word
1092 .I while
1093 is replaced by the word
1094 .IR until ,
1095 the sense of the test is reversed, but the conditional is still tested before
1096 the first iteration.
1097 .PP
1098 In either the
1099 .I if
1100 or the
1101 .I while
1102 statement, you may replace \*(L"(EXPR)\*(R" with a BLOCK, and the conditional
1103 is true if the value of the last command in that block is true.
1104 .PP
1105 The
1106 .I for
1107 loop works exactly like the corresponding
1108 .I while
1109 loop:
1110 .nf
1111
1112 .ne 12
1113         for ($i = 1; $i < 10; $i++) {
1114                 .\|.\|.
1115         }
1116
1117 is the same as
1118
1119         $i = 1;
1120         while ($i < 10) {
1121                 .\|.\|.
1122         } continue {
1123                 $i++;
1124         }
1125 .fi
1126 .PP
1127 The foreach loop iterates over a normal array value and sets the variable
1128 VAR to be each element of the array in turn.
1129 The variable is implicitly local to the loop, and regains its former value
1130 upon exiting the loop.
1131 The \*(L"foreach\*(R" keyword is actually identical to the \*(L"for\*(R" keyword,
1132 so you can use \*(L"foreach\*(R" for readability or \*(L"for\*(R" for brevity.
1133 If VAR is omitted, $_ is set to each value.
1134 If ARRAY is an actual array (as opposed to an expression returning an array
1135 value), you can modify each element of the array
1136 by modifying VAR inside the loop.
1137 Examples:
1138 .nf
1139
1140 .ne 5
1141         for (@ary) { s/foo/bar/; }
1142
1143         foreach $elem (@elements) {
1144                 $elem *= 2;
1145         }
1146
1147 .ne 3
1148         for ((10,9,8,7,6,5,4,3,2,1,\'BOOM\')) {
1149                 print $_, "\en"; sleep(1);
1150         }
1151
1152         for (1..15) { print "Merry Christmas\en"; }
1153
1154 .ne 3
1155         foreach $item (split(/:[\e\e\en:]*/, $ENV{\'TERMCAP\'})) {
1156                 print "Item: $item\en";
1157         }
1158
1159 .fi
1160 .PP
1161 The BLOCK by itself (labeled or not) is equivalent to a loop that executes
1162 once.
1163 Thus you can use any of the loop control statements in it to leave or
1164 restart the block.
1165 The
1166 .I continue
1167 block is optional.
1168 This construct is particularly nice for doing case structures.
1169 .nf
1170
1171 .ne 6
1172         foo: {
1173                 if (/^abc/) { $abc = 1; last foo; }
1174                 if (/^def/) { $def = 1; last foo; }
1175                 if (/^xyz/) { $xyz = 1; last foo; }
1176                 $nothing = 1;
1177         }
1178
1179 .fi
1180 There is no official switch statement in perl, because there
1181 are already several ways to write the equivalent.
1182 In addition to the above, you could write
1183 .nf
1184
1185 .ne 6
1186         foo: {
1187                 $abc = 1, last foo  if /^abc/;
1188                 $def = 1, last foo  if /^def/;
1189                 $xyz = 1, last foo  if /^xyz/;
1190                 $nothing = 1;
1191         }
1192
1193 or
1194
1195 .ne 6
1196         foo: {
1197                 /^abc/ && do { $abc = 1; last foo; };
1198                 /^def/ && do { $def = 1; last foo; };
1199                 /^xyz/ && do { $xyz = 1; last foo; };
1200                 $nothing = 1;
1201         }
1202
1203 or
1204
1205 .ne 6
1206         foo: {
1207                 /^abc/ && ($abc = 1, last foo);
1208                 /^def/ && ($def = 1, last foo);
1209                 /^xyz/ && ($xyz = 1, last foo);
1210                 $nothing = 1;
1211         }
1212
1213 or even
1214
1215 .ne 8
1216         if (/^abc/)
1217                 { $abc = 1; }
1218         elsif (/^def/)
1219                 { $def = 1; }
1220         elsif (/^xyz/)
1221                 { $xyz = 1; }
1222         else
1223                 {$nothing = 1;}
1224
1225 .fi
1226 As it happens, these are all optimized internally to a switch structure,
1227 so perl jumps directly to the desired statement, and you needn't worry
1228 about perl executing a lot of unnecessary statements when you have a string
1229 of 50 elsifs, as long as you are testing the same simple scalar variable
1230 using ==, eq, or pattern matching as above.
1231 (If you're curious as to whether the optimizer has done this for a particular
1232 case statement, you can use the \-D1024 switch to list the syntax tree
1233 before execution.)
1234 .Sh "Simple statements"
1235 The only kind of simple statement is an expression evaluated for its side
1236 effects.
1237 Every expression (simple statement) must be terminated with a semicolon.
1238 Note that this is like C, but unlike Pascal (and
1239 .IR awk ).
1240 .PP
1241 Any simple statement may optionally be followed by a
1242 single modifier, just before the terminating semicolon.
1243 The possible modifiers are:
1244 .nf
1245
1246 .ne 4
1247         if EXPR
1248         unless EXPR
1249         while EXPR
1250         until EXPR
1251
1252 .fi
1253 The
1254 .I if
1255 and
1256 .I unless
1257 modifiers have the expected semantics.
1258 The
1259 .I while
1260 and
1261 .I until
1262 modifiers also have the expected semantics (conditional evaluated first),
1263 except when applied to a do-BLOCK command,
1264 in which case the block executes once before the conditional is evaluated.
1265 This is so that you can write loops like:
1266 .nf
1267
1268 .ne 4
1269         do {
1270                 $_ = <STDIN>;
1271                 .\|.\|.
1272         } until $_ \|eq \|".\|\e\|n";
1273
1274 .fi
1275 (See the
1276 .I do
1277 operator below.  Note also that the loop control commands described later will
1278 NOT work in this construct, since modifiers don't take loop labels.
1279 Sorry.)
1280 .Sh "Expressions"
1281 Since
1282 .I perl
1283 expressions work almost exactly like C expressions, only the differences
1284 will be mentioned here.
1285 .PP
1286 Here's what
1287 .I perl
1288 has that C doesn't:
1289 .Ip ** 8 2
1290 The exponentiation operator.
1291 .Ip **= 8
1292 The exponentiation assignment operator.
1293 .Ip (\|) 8 3
1294 The null list, used to initialize an array to null.
1295 .Ip . 8
1296 Concatenation of two strings.
1297 .Ip .= 8
1298 The concatenation assignment operator.
1299 .Ip eq 8
1300 String equality (== is numeric equality).
1301 For a mnemonic just think of \*(L"eq\*(R" as a string.
1302 (If you are used to the
1303 .I awk
1304 behavior of using == for either string or numeric equality
1305 based on the current form of the comparands, beware!
1306 You must be explicit here.)
1307 .Ip ne 8
1308 String inequality (!= is numeric inequality).
1309 .Ip lt 8
1310 String less than.
1311 .Ip gt 8
1312 String greater than.
1313 .Ip le 8
1314 String less than or equal.
1315 .Ip ge 8
1316 String greater than or equal.
1317 .Ip cmp 8
1318 String comparison, returning -1, 0, or 1.
1319 .Ip <=> 8
1320 Numeric comparison, returning -1, 0, or 1.
1321 .Ip =~ 8 2
1322 Certain operations search or modify the string \*(L"$_\*(R" by default.
1323 This operator makes that kind of operation work on some other string.
1324 The right argument is a search pattern, substitution, or translation.
1325 The left argument is what is supposed to be searched, substituted, or
1326 translated instead of the default \*(L"$_\*(R".
1327 The return value indicates the success of the operation.
1328 (If the right argument is an expression other than a search pattern,
1329 substitution, or translation, it is interpreted as a search pattern
1330 at run time.
1331 This is less efficient than an explicit search, since the pattern must
1332 be compiled every time the expression is evaluated.)
1333 The precedence of this operator is lower than unary minus and autoincrement/decrement, but higher than everything else.
1334 .Ip !~ 8
1335 Just like =~ except the return value is negated.
1336 .Ip x 8
1337 The repetition operator.
1338 Returns a string consisting of the left operand repeated the
1339 number of times specified by the right operand.
1340 .nf
1341
1342         print \'\-\' x 80;              # print row of dashes
1343         print \'\-\' x80;               # illegal, x80 is identifier
1344
1345         print "\et" x ($tab/8), \' \' x ($tab%8);       # tab over
1346
1347 .fi
1348 .Ip x= 8
1349 The repetition assignment operator.
1350 .Ip .\|. 8
1351 The range operator, which is really two different operators depending
1352 on the context.
1353 In an array context, returns an array of values counting (by ones)
1354 from the left value to the right value.
1355 This is useful for writing \*(L"for (1..10)\*(R" loops and for doing
1356 slice operations on arrays.
1357 .Sp
1358 In a scalar context, .\|. returns a boolean value.
1359 The operator is bistable, like a flip-flop..
1360 Each .\|. operator maintains its own boolean state.
1361 It is false as long as its left operand is false.
1362 Once the left operand is true, the range operator stays true
1363 until the right operand is true,
1364 AFTER which the range operator becomes false again.
1365 (It doesn't become false till the next time the range operator is evaluated.
1366 It can become false on the same evaluation it became true, but it still returns
1367 true once.)
1368 The right operand is not evaluated while the operator is in the \*(L"false\*(R" state,
1369 and the left operand is not evaluated while the operator is in the \*(L"true\*(R" state.
1370 The scalar .\|. operator is primarily intended for doing line number ranges
1371 after
1372 the fashion of \fIsed\fR or \fIawk\fR.
1373 The precedence is a little lower than || and &&.
1374 The value returned is either the null string for false, or a sequence number
1375 (beginning with 1) for true.
1376 The sequence number is reset for each range encountered.
1377 The final sequence number in a range has the string \'E0\' appended to it, which
1378 doesn't affect its numeric value, but gives you something to search for if you
1379 want to exclude the endpoint.
1380 You can exclude the beginning point by waiting for the sequence number to be
1381 greater than 1.
1382 If either operand of scalar .\|. is static, that operand is implicitly compared
1383 to the $. variable, the current line number.
1384 Examples:
1385 .nf
1386
1387 .ne 6
1388 As a scalar operator:
1389     if (101 .\|. 200) { print; }        # print 2nd hundred lines
1390
1391     next line if (1 .\|. /^$/); # skip header lines
1392
1393     s/^/> / if (/^$/ .\|. eof());       # quote body
1394
1395 .ne 4
1396 As an array operator:
1397     for (101 .\|. 200) { print; }       # print $_ 100 times
1398
1399     @foo = @foo[$[ .\|. $#foo]; # an expensive no-op
1400     @foo = @foo[$#foo-4 .\|. $#foo];    # slice last 5 items
1401
1402 .fi
1403 .Ip \-x 8
1404 A file test.
1405 This unary operator takes one argument, either a filename or a filehandle,
1406 and tests the associated file to see if something is true about it.
1407 If the argument is omitted, tests $_, except for \-t, which tests
1408 .IR STDIN .
1409 It returns 1 for true and \'\' for false, or the undefined value if the
1410 file doesn't exist.
1411 Precedence is higher than logical and relational operators, but lower than
1412 arithmetic operators.
1413 The operator may be any of:
1414 .nf
1415         \-r     File is readable by effective uid.
1416         \-w     File is writable by effective uid.
1417         \-x     File is executable by effective uid.
1418         \-o     File is owned by effective uid.
1419         \-R     File is readable by real uid.
1420         \-W     File is writable by real uid.
1421         \-X     File is executable by real uid.
1422         \-O     File is owned by real uid.
1423         \-e     File exists.
1424         \-z     File has zero size.
1425         \-s     File has non-zero size (returns size).
1426         \-f     File is a plain file.
1427         \-d     File is a directory.
1428         \-l     File is a symbolic link.
1429         \-p     File is a named pipe (FIFO).
1430         \-S     File is a socket.
1431         \-b     File is a block special file.
1432         \-c     File is a character special file.
1433         \-u     File has setuid bit set.
1434         \-g     File has setgid bit set.
1435         \-k     File has sticky bit set.
1436         \-t     Filehandle is opened to a tty.
1437         \-T     File is a text file.
1438         \-B     File is a binary file (opposite of \-T).
1439         \-M     Age of file in days when script started.
1440         \-A     Same for access time.
1441         \-C     Same for inode change time.
1442
1443 .fi
1444 The interpretation of the file permission operators \-r, \-R, \-w, \-W, \-x and \-X
1445 is based solely on the mode of the file and the uids and gids of the user.
1446 There may be other reasons you can't actually read, write or execute the file.
1447 Also note that, for the superuser, \-r, \-R, \-w and \-W always return 1, and 
1448 \-x and \-X return 1 if any execute bit is set in the mode.
1449 Scripts run by the superuser may thus need to do a stat() in order to determine
1450 the actual mode of the file, or temporarily set the uid to something else.
1451 .Sp
1452 Example:
1453 .nf
1454 .ne 7
1455         
1456         while (<>) {
1457                 chop;
1458                 next unless \-f $_;     # ignore specials
1459                 .\|.\|.
1460         }
1461
1462 .fi
1463 Note that \-s/a/b/ does not do a negated substitution.
1464 Saying \-exp($foo) still works as expected, however\*(--only single letters
1465 following a minus are interpreted as file tests.
1466 .Sp
1467 The \-T and \-B switches work as follows.
1468 The first block or so of the file is examined for odd characters such as
1469 strange control codes or metacharacters.
1470 If too many odd characters (>10%) are found, it's a \-B file, otherwise it's a \-T file.
1471 Also, any file containing null in the first block is considered a binary file.
1472 If \-T or \-B is used on a filehandle, the current stdio buffer is examined
1473 rather than the first block.
1474 Both \-T and \-B return TRUE on a null file, or a file at EOF when testing
1475 a filehandle.
1476 .PP
1477 If any of the file tests (or either stat operator) are given the special
1478 filehandle consisting of a solitary underline, then the stat structure
1479 of the previous file test (or stat operator) is used, saving a system
1480 call.
1481 (This doesn't work with \-t, and you need to remember that lstat and -l
1482 will leave values in the stat structure for the symbolic link, not the
1483 real file.)
1484 Example:
1485 .nf
1486
1487         print "Can do.\en" if -r $a || -w _ || -x _;
1488
1489 .ne 9
1490         stat($filename);
1491         print "Readable\en" if -r _;
1492         print "Writable\en" if -w _;
1493         print "Executable\en" if -x _;
1494         print "Setuid\en" if -u _;
1495         print "Setgid\en" if -g _;
1496         print "Sticky\en" if -k _;
1497         print "Text\en" if -T _;
1498         print "Binary\en" if -B _;
1499
1500 .fi
1501 .PP
1502 Here is what C has that
1503 .I perl
1504 doesn't:
1505 .Ip "unary &" 12
1506 Address-of operator.
1507 .Ip "unary *" 12
1508 Dereference-address operator.
1509 .Ip "(TYPE)" 12
1510 Type casting operator.
1511 .PP
1512 Like C,
1513 .I perl
1514 does a certain amount of expression evaluation at compile time, whenever
1515 it determines that all of the arguments to an operator are static and have
1516 no side effects.
1517 In particular, string concatenation happens at compile time between literals that don't do variable substitution.
1518 Backslash interpretation also happens at compile time.
1519 You can say
1520 .nf
1521
1522 .ne 2
1523         \'Now is the time for all\' . "\|\e\|n" .
1524         \'good men to come to.\'
1525
1526 .fi
1527 and this all reduces to one string internally.
1528 .PP
1529 The autoincrement operator has a little extra built-in magic to it.
1530 If you increment a variable that is numeric, or that has ever been used in
1531 a numeric context, you get a normal increment.
1532 If, however, the variable has only been used in string contexts since it
1533 was set, and has a value that is not null and matches the
1534 pattern /^[a\-zA\-Z]*[0\-9]*$/, the increment is done
1535 as a string, preserving each character within its range, with carry:
1536 .nf
1537
1538         print ++($foo = \'99\');        # prints \*(L'100\*(R'
1539         print ++($foo = \'a0\');        # prints \*(L'a1\*(R'
1540         print ++($foo = \'Az\');        # prints \*(L'Ba\*(R'
1541         print ++($foo = \'zz\');        # prints \*(L'aaa\*(R'
1542
1543 .fi
1544 The autodecrement is not magical.
1545 .PP
1546 The range operator (in an array context) makes use of the magical
1547 autoincrement algorithm if the minimum and maximum are strings.
1548 You can say
1549
1550         @alphabet = (\'A\' .. \'Z\');
1551
1552 to get all the letters of the alphabet, or
1553
1554         $hexdigit = (0 .. 9, \'a\' .. \'f\')[$num & 15];
1555
1556 to get a hexadecimal digit, or
1557
1558         @z2 = (\'01\' .. \'31\');  print @z2[$mday];
1559
1560 to get dates with leading zeros.
1561 (If the final value specified is not in the sequence that the magical increment
1562 would produce, the sequence goes until the next value would be longer than
1563 the final value specified.)
1564 .PP
1565 The || and && operators differ from C's in that, rather than returning 0 or 1,
1566 they return the last value evaluated. 
1567 Thus, a portable way to find out the home directory might be:
1568 .nf
1569
1570         $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
1571             (getpwuid($<))[7] || die "You're homeless!\en";
1572
1573 .fi