1PERLRUN(1) Perl Programmers Reference Guide PERLRUN(1)
2
3
4
6 perlrun - how to execute the Perl interpreter
7
9 perl [ -sTtuUWX ] [ -hv ] [ -V[:configvar] ]
10 [ -cw ] [ -d[t][:debugger] ] [ -D[number/list] ]
11 [ -pna ] [ -Fpattern ] [ -l[octal] ] [ -0[octal/hexadecimal] ]
12 [ -Idir ] [ -m[-]module ] [ -M[-]'module...' ] [ -f ]
13 [ -C [number/list] ] [ -S ] [ -x[dir] ]
14 [ -i[extension] ]
15 [ [-e|-E] 'command' ] [ -- ] [ programfile ] [ argument ]...
16
18 The normal way to run a Perl program is by making it directly
19 executable, or else by passing the name of the source file as an
20 argument on the command line. (An interactive Perl environment is also
21 possible--see perldebug for details on how to do that.) Upon startup,
22 Perl looks for your program in one of the following places:
23
24 1. Specified line by line via -e or -E switches on the command line.
25
26 2. Contained in the file specified by the first filename on the
27 command line. (Note that systems supporting the "#!" notation
28 invoke interpreters this way. See "Location of Perl".)
29
30 3. Passed in implicitly via standard input. This works only if there
31 are no filename arguments--to pass arguments to a STDIN-read
32 program you must explicitly specify a "-" for the program name.
33
34 With methods 2 and 3, Perl starts parsing the input file from the
35 beginning, unless you've specified a -x switch, in which case it scans
36 for the first line starting with "#!" and containing the word "perl",
37 and starts there instead. This is useful for running a program
38 embedded in a larger message. (In this case you would indicate the end
39 of the program using the "__END__" token.)
40
41 The "#!" line is always examined for switches as the line is being
42 parsed. Thus, if you're on a machine that allows only one argument
43 with the "#!" line, or worse, doesn't even recognize the "#!" line, you
44 still can get consistent switch behaviour regardless of how Perl was
45 invoked, even if -x was used to find the beginning of the program.
46
47 Because historically some operating systems silently chopped off kernel
48 interpretation of the "#!" line after 32 characters, some switches may
49 be passed in on the command line, and some may not; you could even get
50 a "-" without its letter, if you're not careful. You probably want to
51 make sure that all your switches fall either before or after that
52 32-character boundary. Most switches don't actually care if they're
53 processed redundantly, but getting a "-" instead of a complete switch
54 could cause Perl to try to execute standard input instead of your
55 program. And a partial -I switch could also cause odd results.
56
57 Some switches do care if they are processed twice, for instance
58 combinations of -l and -0. Either put all the switches after the
59 32-character boundary (if applicable), or replace the use of -0digits
60 by "BEGIN{ $/ = "\0digits"; }".
61
62 Parsing of the "#!" switches starts wherever "perl" is mentioned in the
63 line. The sequences "-*" and "- " are specifically ignored so that you
64 could, if you were so inclined, say
65
66 #!/bin/sh
67 #! -*-perl-*-
68 eval 'exec perl -x -wS $0 ${1+"$@"}'
69 if 0;
70
71 to let Perl see the -p switch.
72
73 A similar trick involves the env program, if you have it.
74
75 #!/usr/bin/env perl
76
77 The examples above use a relative path to the perl interpreter, getting
78 whatever version is first in the user's path. If you want a specific
79 version of Perl, say, perl5.005_57, you should place that directly in
80 the "#!" line's path.
81
82 If the "#!" line does not contain the word "perl" nor the word "indir"
83 the program named after the "#!" is executed instead of the Perl
84 interpreter. This is slightly bizarre, but it helps people on machines
85 that don't do "#!", because they can tell a program that their SHELL is
86 /usr/bin/perl, and Perl will then dispatch the program to the correct
87 interpreter for them.
88
89 After locating your program, Perl compiles the entire program to an
90 internal form. If there are any compilation errors, execution of the
91 program is not attempted. (This is unlike the typical shell script,
92 which might run part-way through before finding a syntax error.)
93
94 If the program is syntactically correct, it is executed. If the
95 program runs off the end without hitting an exit() or die() operator,
96 an implicit exit(0) is provided to indicate successful completion.
97
98 #! and quoting on non-Unix systems
99 Unix's "#!" technique can be simulated on other systems:
100
101 OS/2
102 Put
103
104 extproc perl -S -your_switches
105
106 as the first line in "*.cmd" file (-S due to a bug in cmd.exe's
107 `extproc' handling).
108
109 MS-DOS
110 Create a batch file to run your program, and codify it in
111 "ALTERNATE_SHEBANG" (see the dosish.h file in the source
112 distribution for more information).
113
114 Win95/NT
115 The Win95/NT installation, when using the ActiveState installer for
116 Perl, will modify the Registry to associate the .pl extension with
117 the perl interpreter. If you install Perl by other means
118 (including building from the sources), you may have to modify the
119 Registry yourself. Note that this means you can no longer tell the
120 difference between an executable Perl program and a Perl library
121 file.
122
123 VMS Put
124
125 $ perl -mysw 'f$env("procedure")' 'p1' 'p2' 'p3' 'p4' 'p5' 'p6' 'p7' 'p8' !
126 $ exit++ + ++$status != 0 and $exit = $status = undef;
127
128 at the top of your program, where -mysw are any command line
129 switches you want to pass to Perl. You can now invoke the program
130 directly, by saying "perl program", or as a DCL procedure, by
131 saying @program (or implicitly via DCL$PATH by just using the name
132 of the program).
133
134 This incantation is a bit much to remember, but Perl will display
135 it for you if you say "perl "-V:startperl"".
136
137 Command-interpreters on non-Unix systems have rather different ideas on
138 quoting than Unix shells. You'll need to learn the special characters
139 in your command-interpreter ("*", "\" and """ are common) and how to
140 protect whitespace and these characters to run one-liners (see -e
141 below).
142
143 On some systems, you may have to change single-quotes to double ones,
144 which you must not do on Unix or Plan 9 systems. You might also have
145 to change a single % to a %%.
146
147 For example:
148
149 # Unix
150 perl -e 'print "Hello world\n"'
151
152 # MS-DOS, etc.
153 perl -e "print \"Hello world\n\""
154
155 # VMS
156 perl -e "print ""Hello world\n"""
157
158 The problem is that none of this is reliable: it depends on the command
159 and it is entirely possible neither works. If 4DOS were the command
160 shell, this would probably work better:
161
162 perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>""
163
164 CMD.EXE in Windows NT slipped a lot of standard Unix functionality in
165 when nobody was looking, but just try to find documentation for its
166 quoting rules.
167
168 There is no general solution to all of this. It's just a mess.
169
170 Location of Perl
171 It may seem obvious to say, but Perl is useful only when users can
172 easily find it. When possible, it's good for both /usr/bin/perl and
173 /usr/local/bin/perl to be symlinks to the actual binary. If that can't
174 be done, system administrators are strongly encouraged to put (symlinks
175 to) perl and its accompanying utilities into a directory typically
176 found along a user's PATH, or in some other obvious and convenient
177 place.
178
179 In this documentation, "#!/usr/bin/perl" on the first line of the
180 program will stand in for whatever method works on your system. You
181 are advised to use a specific path if you care about a specific
182 version.
183
184 #!/usr/local/bin/perl5.00554
185
186 or if you just want to be running at least version, place a statement
187 like this at the top of your program:
188
189 use 5.005_54;
190
191 Command Switches
192 As with all standard commands, a single-character switch may be
193 clustered with the following switch, if any.
194
195 #!/usr/bin/perl -spi.orig # same as -s -p -i.orig
196
197 Switches include:
198
199 -0[octal/hexadecimal]
200 specifies the input record separator ($/) as an octal or
201 hexadecimal number. If there are no digits, the null character is
202 the separator. Other switches may precede or follow the digits.
203 For example, if you have a version of find which can print
204 filenames terminated by the null character, you can say this:
205
206 find . -name '*.orig' -print0 | perl -n0e unlink
207
208 The special value 00 will cause Perl to slurp files in paragraph
209 mode. Any value 0400 or above will cause Perl to slurp files
210 whole, but by convention the value 0777 is the one normally used
211 for this purpose.
212
213 You can also specify the separator character using hexadecimal
214 notation: -0xHHH..., where the "H" are valid hexadecimal digits.
215 Unlike the octal form, this one may be used to specify any Unicode
216 character, even those beyond 0xFF. So if you really want a record
217 separator of 0777, specify it as -0x1FF. (This means that you
218 cannot use the -x option with a directory name that consists of
219 hexadecimal digits, or else Perl will think you have specified a
220 hex number to -0.)
221
222 -a turns on autosplit mode when used with a -n or -p. An implicit
223 split command to the @F array is done as the first thing inside
224 the implicit while loop produced by the -n or -p.
225
226 perl -ane 'print pop(@F), "\n";'
227
228 is equivalent to
229
230 while (<>) {
231 @F = split(' ');
232 print pop(@F), "\n";
233 }
234
235 An alternate delimiter may be specified using -F.
236
237 -C [number/list]
238 The -C flag controls some of the Perl Unicode features.
239
240 As of 5.8.1, the -C can be followed either by a number or a list
241 of option letters. The letters, their numeric values, and effects
242 are as follows; listing the letters is equal to summing the
243 numbers.
244
245 I 1 STDIN is assumed to be in UTF-8
246 O 2 STDOUT will be in UTF-8
247 E 4 STDERR will be in UTF-8
248 S 7 I + O + E
249 i 8 UTF-8 is the default PerlIO layer for input streams
250 o 16 UTF-8 is the default PerlIO layer for output streams
251 D 24 i + o
252 A 32 the @ARGV elements are expected to be strings encoded
253 in UTF-8
254 L 64 normally the "IOEioA" are unconditional, the L makes
255 them conditional on the locale environment variables
256 (the LC_ALL, LC_TYPE, and LANG, in the order of
257 decreasing precedence) -- if the variables indicate
258 UTF-8, then the selected "IOEioA" are in effect
259 a 256 Set ${^UTF8CACHE} to -1, to run the UTF-8 caching
260 code in debugging mode.
261
262 For example, -COE and -C6 will both turn on UTF-8-ness on both
263 STDOUT and STDERR. Repeating letters is just redundant, not
264 cumulative nor toggling.
265
266 The "io" options mean that any subsequent open() (or similar I/O
267 operations) in the current file scope will have the ":utf8" PerlIO
268 layer implicitly applied to them, in other words, UTF-8 is
269 expected from any input stream, and UTF-8 is produced to any
270 output stream. This is just the default, with explicit layers in
271 open() and with binmode() one can manipulate streams as usual.
272
273 -C on its own (not followed by any number or option list), or the
274 empty string "" for the "PERL_UNICODE" environment variable, has
275 the same effect as -CSDL. In other words, the standard I/O
276 handles and the default "open()" layer are UTF-8-fied but only if
277 the locale environment variables indicate a UTF-8 locale. This
278 behaviour follows the implicit (and problematic) UTF-8 behaviour
279 of Perl 5.8.0. (See "UTF-8 no longer default under UTF-8 locales"
280 in perl581delta.)
281
282 You can use -C0 (or "0" for "PERL_UNICODE") to explicitly disable
283 all the above Unicode features.
284
285 The read-only magic variable "${^UNICODE}" reflects the numeric
286 value of this setting. This variable is set during Perl startup
287 and is thereafter read-only. If you want runtime effects, use the
288 three-arg open() (see "open" in perlfunc), the two-arg binmode()
289 (see "binmode" in perlfunc), and the "open" pragma (see open).
290
291 (In Perls earlier than 5.8.1 the -C switch was a Win32-only switch
292 that enabled the use of Unicode-aware "wide system call" Win32
293 APIs. This feature was practically unused, however, and the
294 command line switch was therefore "recycled".)
295
296 Note: Since perl 5.10.1, if the -C option is used on the "#!"
297 line, it must be specified on the command line as well, since the
298 standard streams are already set up at this point in the execution
299 of the perl interpreter. You can also use binmode() to set the
300 encoding of an I/O stream.
301
302 -c causes Perl to check the syntax of the program and then exit
303 without executing it. Actually, it will execute and "BEGIN",
304 "UNITCHECK", or "CHECK" blocks and any "use" statements: these are
305 considered as occurring outside the execution of your program.
306 "INIT" and "END" blocks, however, will be skipped.
307
308 -d
309 -dt runs the program under the Perl debugger. See perldebug. If t is
310 specified, it indicates to the debugger that threads will be used
311 in the code being debugged.
312
313 -d:MOD[=bar,baz]
314 -dt:MOD[=bar,baz]
315 runs the program under the control of a debugging, profiling, or
316 tracing module installed as "Devel::MOD". E.g., -d:DProf executes
317 the program using the "Devel::DProf" profiler. As with the -M
318 flag, options may be passed to the "Devel::MOD" package where they
319 will be received and interpreted by the "Devel::MOD::import"
320 routine. Again, like -M, use --d:-MOD to call
321 "Devel::MOD::unimport" instead of import. The comma-separated
322 list of options must follow a "=" character. If t is specified,
323 it indicates to the debugger that threads will be used in the code
324 being debugged. See perldebug.
325
326 -Dletters
327 -Dnumber
328 sets debugging flags. To watch how it executes your program, use
329 -Dtls. (This works only if debugging is compiled into your Perl.)
330 Another nice value is -Dx, which lists your compiled syntax tree.
331 And -Dr displays compiled regular expressions; the format of the
332 output is explained in perldebguts.
333
334 As an alternative, specify a number instead of list of letters
335 (e.g., -D14 is equivalent to -Dtls):
336
337 1 p Tokenizing and parsing (with v, displays parse stack)
338 2 s Stack snapshots (with v, displays all stacks)
339 4 l Context (loop) stack processing
340 8 t Trace execution
341 16 o Method and overloading resolution
342 32 c String/numeric conversions
343 64 P Print profiling info, source file input state
344 128 m Memory and SV allocation
345 256 f Format processing
346 512 r Regular expression parsing and execution
347 1024 x Syntax tree dump
348 2048 u Tainting checks
349 4096 U Unofficial, User hacking (reserved for private,
350 unreleased use)
351 8192 H Hash dump -- usurps values()
352 16384 X Scratchpad allocation
353 32768 D Cleaning up
354 131072 T Tokenizing
355 262144 R Include reference counts of dumped variables (eg when
356 using -Ds)
357 524288 J show s,t,P-debug (don't Jump over) on opcodes within
358 package DB
359 1048576 v Verbose: use in conjunction with other flags
360 2097152 C Copy On Write
361 4194304 A Consistency checks on internal structures
362 8388608 q quiet - currently only suppresses the "EXECUTING"
363 message
364 16777216 M trace smart match resolution
365 33554432 B dump suBroutine definitions, including special Blocks
366 like BEGIN
367
368 All these flags require -DDEBUGGING when you compile the Perl
369 executable (but see ":opd" in Devel::Peek or "'debug' mode" in re
370 which may change this). See the INSTALL file in the Perl source
371 distribution for how to do this. This flag is automatically set
372 if you include -g option when "Configure" asks you about
373 optimizer/debugger flags.
374
375 If you're just trying to get a print out of each line of Perl code
376 as it executes, the way that "sh -x" provides for shell scripts,
377 you can't use Perl's -D switch. Instead do this
378
379 # If you have "env" utility
380 env PERLDB_OPTS="NonStop=1 AutoTrace=1 frame=2" perl -dS program
381
382 # Bourne shell syntax
383 $ PERLDB_OPTS="NonStop=1 AutoTrace=1 frame=2" perl -dS program
384
385 # csh syntax
386 % (setenv PERLDB_OPTS "NonStop=1 AutoTrace=1 frame=2"; perl -dS program)
387
388 See perldebug for details and variations.
389
390 -e commandline
391 may be used to enter one line of program. If -e is given, Perl
392 will not look for a filename in the argument list. Multiple -e
393 commands may be given to build up a multi-line script. Make sure
394 to use semicolons where you would in a normal program.
395
396 -E commandline
397 behaves just like -e, except that it implicitly enables all
398 optional features (in the main compilation unit). See feature.
399
400 -f Disable executing $Config{sitelib}/sitecustomize.pl at startup.
401
402 Perl can be built so that it by default will try to execute
403 $Config{sitelib}/sitecustomize.pl at startup (in a BEGIN block).
404 This is a hook that allows the sysadmin to customize how Perl
405 behaves. It can for instance be used to add entries to the @INC
406 array to make Perl find modules in non-standard locations.
407
408 Perl actually inserts the following code:
409
410 BEGIN {
411 do { local $!; -f "$Config{sitelib}/sitecustomize.pl"; }
412 && do "$Config{sitelib}/sitecustomize.pl";
413 }
414
415 Since it is an actual "do" (not a "require"), sitecustomize.pl
416 doesn't need to return a true value. The code is run in package
417 "main", in its own lexical scope. However, if the script dies, $@
418 will not be set.
419
420 The value of $Config{sitelib} is also determined in C code and not
421 read from "Config.pm", which is not loaded.
422
423 The code is executed very early. For example, any changes made to
424 @INC will show up in the output of `perl -V`. Of course, "END"
425 blocks will be likewise executed very late.
426
427 To determine at runtime if this capability has been compiled in
428 your perl, you can check the value of $Config{usesitecustomize}.
429
430 -Fpattern
431 specifies the pattern to split on if -a is also in effect. The
432 pattern may be surrounded by "//", "", or '', otherwise it will be
433 put in single quotes. You can't use literal whitespace in the
434 pattern.
435
436 -h prints a summary of the options.
437
438 -i[extension]
439 specifies that files processed by the "<>" construct are to be
440 edited in-place. It does this by renaming the input file, opening
441 the output file by the original name, and selecting that output
442 file as the default for print() statements. The extension, if
443 supplied, is used to modify the name of the old file to make a
444 backup copy, following these rules:
445
446 If no extension is supplied, no backup is made and the current
447 file is overwritten.
448
449 If the extension doesn't contain a "*", then it is appended to the
450 end of the current filename as a suffix. If the extension does
451 contain one or more "*" characters, then each "*" is replaced with
452 the current filename. In Perl terms, you could think of this as:
453
454 ($backup = $extension) =~ s/\*/$file_name/g;
455
456 This allows you to add a prefix to the backup file, instead of (or
457 in addition to) a suffix:
458
459 $ perl -pi'orig_*' -e 's/bar/baz/' fileA # backup to
460 # 'orig_fileA'
461
462 Or even to place backup copies of the original files into another
463 directory (provided the directory already exists):
464
465 $ perl -pi'old/*.orig' -e 's/bar/baz/' fileA # backup to
466 # 'old/fileA.orig'
467
468 These sets of one-liners are equivalent:
469
470 $ perl -pi -e 's/bar/baz/' fileA # overwrite current file
471 $ perl -pi'*' -e 's/bar/baz/' fileA # overwrite current file
472
473 $ perl -pi'.orig' -e 's/bar/baz/' fileA # backup to 'fileA.orig'
474 $ perl -pi'*.orig' -e 's/bar/baz/' fileA # backup to 'fileA.orig'
475
476 From the shell, saying
477
478 $ perl -p -i.orig -e "s/foo/bar/; ... "
479
480 is the same as using the program:
481
482 #!/usr/bin/perl -pi.orig
483 s/foo/bar/;
484
485 which is equivalent to
486
487 #!/usr/bin/perl
488 $extension = '.orig';
489 LINE: while (<>) {
490 if ($ARGV ne $oldargv) {
491 if ($extension !~ /\*/) {
492 $backup = $ARGV . $extension;
493 }
494 else {
495 ($backup = $extension) =~ s/\*/$ARGV/g;
496 }
497 rename($ARGV, $backup);
498 open(ARGVOUT, ">$ARGV");
499 select(ARGVOUT);
500 $oldargv = $ARGV;
501 }
502 s/foo/bar/;
503 }
504 continue {
505 print; # this prints to original filename
506 }
507 select(STDOUT);
508
509 except that the -i form doesn't need to compare $ARGV to $oldargv
510 to know when the filename has changed. It does, however, use
511 ARGVOUT for the selected filehandle. Note that STDOUT is restored
512 as the default output filehandle after the loop.
513
514 As shown above, Perl creates the backup file whether or not any
515 output is actually changed. So this is just a fancy way to copy
516 files:
517
518 $ perl -p -i'/some/file/path/*' -e 1 file1 file2 file3...
519 or
520 $ perl -p -i'.orig' -e 1 file1 file2 file3...
521
522 You can use "eof" without parentheses to locate the end of each
523 input file, in case you want to append to each file, or reset line
524 numbering (see example in "eof" in perlfunc).
525
526 If, for a given file, Perl is unable to create the backup file as
527 specified in the extension then it will skip that file and
528 continue on with the next one (if it exists).
529
530 For a discussion of issues surrounding file permissions and -i,
531 see "Why does Perl let me delete read-only files? Why does -i
532 clobber protected files? Isn't this a bug in Perl?" in perlfaq5.
533
534 You cannot use -i to create directories or to strip extensions
535 from files.
536
537 Perl does not expand "~" in filenames, which is good, since some
538 folks use it for their backup files:
539
540 $ perl -pi~ -e 's/foo/bar/' file1 file2 file3...
541
542 Note that because -i renames or deletes the original file before
543 creating a new file of the same name, Unix-style soft and hard
544 links will not be preserved.
545
546 Finally, the -i switch does not impede execution when no files are
547 given on the command line. In this case, no backup is made (the
548 original file cannot, of course, be determined) and processing
549 proceeds from STDIN to STDOUT as might be expected.
550
551 -Idirectory
552 Directories specified by -I are prepended to the search path for
553 modules (@INC).
554
555 -l[octnum]
556 enables automatic line-ending processing. It has two separate
557 effects. First, it automatically chomps $/ (the input record
558 separator) when used with -n or -p. Second, it assigns "$\" (the
559 output record separator) to have the value of octnum so that any
560 print statements will have that separator added back on. If
561 octnum is omitted, sets "$\" to the current value of $/. For
562 instance, to trim lines to 80 columns:
563
564 perl -lpe 'substr($_, 80) = ""'
565
566 Note that the assignment "$\ = $/" is done when the switch is
567 processed, so the input record separator can be different than the
568 output record separator if the -l switch is followed by a -0
569 switch:
570
571 gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
572
573 This sets "$\" to newline and then sets $/ to the null character.
574
575 -m[-]module
576 -M[-]module
577 -M[-]'module ...'
578 -[mM][-]module=arg[,arg]...
579 -mmodule executes "use" module "();" before executing your
580 program.
581
582 -Mmodule executes "use" module ";" before executing your program.
583 You can use quotes to add extra code after the module name, e.g.,
584 '-MMODULE qw(foo bar)'.
585
586 If the first character after the -M or -m is a dash (-) then the
587 'use' is replaced with 'no'.
588
589 A little builtin syntactic sugar means you can also say
590 -mMODULE=foo,bar or -MMODULE=foo,bar as a shortcut for '-MMODULE
591 qw(foo bar)'. This avoids the need to use quotes when importing
592 symbols. The actual code generated by -MMODULE=foo,bar is "use
593 module split(/,/,q{foo,bar})". Note that the "=" form removes the
594 distinction between -m and -M.
595
596 A consequence of this is that -MMODULE=number never does a version
597 check, unless "MODULE::import()" itself is set up to do a version
598 check, which could happen for example if MODULE inherits from
599 Exporter.
600
601 -n causes Perl to assume the following loop around your program,
602 which makes it iterate over filename arguments somewhat like sed
603 -n or awk:
604
605 LINE:
606 while (<>) {
607 ... # your program goes here
608 }
609
610 Note that the lines are not printed by default. See "-p" to have
611 lines printed. If a file named by an argument cannot be opened
612 for some reason, Perl warns you about it and moves on to the next
613 file.
614
615 Also note that "<>" passes command line arguments to "open" in
616 perlfunc, which doesn't necessarily interpret them as file names.
617 See perlop for possible security implications.
618
619 Here is an efficient way to delete all files that haven't been
620 modified for at least a week:
621
622 find . -mtime +7 -print | perl -nle unlink
623
624 This is faster than using the -exec switch of find because you
625 don't have to start a process on every filename found. It does
626 suffer from the bug of mishandling newlines in pathnames, which
627 you can fix if you follow the example under -0.
628
629 "BEGIN" and "END" blocks may be used to capture control before or
630 after the implicit program loop, just as in awk.
631
632 -p causes Perl to assume the following loop around your program,
633 which makes it iterate over filename arguments somewhat like sed:
634
635 LINE:
636 while (<>) {
637 ... # your program goes here
638 } continue {
639 print or die "-p destination: $!\n";
640 }
641
642 If a file named by an argument cannot be opened for some reason,
643 Perl warns you about it, and moves on to the next file. Note that
644 the lines are printed automatically. An error occurring during
645 printing is treated as fatal. To suppress printing use the -n
646 switch. A -p overrides a -n switch.
647
648 "BEGIN" and "END" blocks may be used to capture control before or
649 after the implicit loop, just as in awk.
650
651 -s enables rudimentary switch parsing for switches on the command
652 line after the program name but before any filename arguments (or
653 before an argument of --). Any switch found there is removed from
654 @ARGV and sets the corresponding variable in the Perl program.
655 The following program prints "1" if the program is invoked with a
656 -xyz switch, and "abc" if it is invoked with -xyz=abc.
657
658 #!/usr/bin/perl -s
659 if ($xyz) { print "$xyz\n" }
660
661 Do note that a switch like --help creates the variable "${-help}",
662 which is not compliant with "use strict "refs"". Also, when using
663 this option on a script with warnings enabled you may get a lot of
664 spurious "used only once" warnings.
665
666 -S makes Perl use the PATH environment variable to search for the
667 program unless the name of the program contains path separators.
668
669 On some platforms, this also makes Perl append suffixes to the
670 filename while searching for it. For example, on Win32 platforms,
671 the ".bat" and ".cmd" suffixes are appended if a lookup for the
672 original name fails, and if the name does not already end in one
673 of those suffixes. If your Perl was compiled with "DEBUGGING"
674 turned on, using the -Dp switch to Perl shows how the search
675 progresses.
676
677 Typically this is used to emulate "#!" startup on platforms that
678 don't support "#!". It's also convenient when debugging a script
679 that uses "#!", and is thus normally found by the shell's $PATH
680 search mechanism.
681
682 This example works on many platforms that have a shell compatible
683 with Bourne shell:
684
685 #!/usr/bin/perl
686 eval 'exec /usr/bin/perl -wS $0 ${1+"$@"}'
687 if $running_under_some_shell;
688
689 The system ignores the first line and feeds the program to
690 /bin/sh, which proceeds to try to execute the Perl program as a
691 shell script. The shell executes the second line as a normal
692 shell command, and thus starts up the Perl interpreter. On some
693 systems $0 doesn't always contain the full pathname, so the -S
694 tells Perl to search for the program if necessary. After Perl
695 locates the program, it parses the lines and ignores them because
696 the variable $running_under_some_shell is never true. If the
697 program will be interpreted by csh, you will need to replace
698 "${1+"$@"}" with $*, even though that doesn't understand embedded
699 spaces (and such) in the argument list. To start up sh rather
700 than csh, some systems may have to replace the "#!" line with a
701 line containing just a colon, which will be politely ignored by
702 Perl. Other systems can't control that, and need a totally
703 devious construct that will work under any of csh, sh, or Perl,
704 such as the following:
705
706 eval '(exit $?0)' && eval 'exec perl -wS $0 ${1+"$@"}'
707 & eval 'exec /usr/bin/perl -wS $0 $argv:q'
708 if $running_under_some_shell;
709
710 If the filename supplied contains directory separators (and so is
711 an absolute or relative pathname), and if that file is not found,
712 platforms that append file extensions will do so and try to look
713 for the file with those extensions added, one by one.
714
715 On DOS-like platforms, if the program does not contain directory
716 separators, it will first be searched for in the current directory
717 before being searched for on the PATH. On Unix platforms, the
718 program will be searched for strictly on the PATH.
719
720 -t Like -T, but taint checks will issue warnings rather than fatal
721 errors. These warnings can now be controlled normally with "no
722 warnings qw(taint)".
723
724 Note: This is not a substitute for "-T"! This is meant to be used
725 only as a temporary development aid while securing legacy code:
726 for real production code and for new secure code written from
727 scratch, always use the real -T.
728
729 -T turns on "taint" so you can test them. Ordinarily these checks
730 are done only when running setuid or setgid. It's a good idea to
731 turn them on explicitly for programs that run on behalf of someone
732 else whom you might not necessarily trust, such as CGI programs or
733 any internet servers you might write in Perl. See perlsec for
734 details. For security reasons, this option must be seen by Perl
735 quite early; usually this means it must appear early on the
736 command line or in the "#!" line for systems which support that
737 construct.
738
739 -u This switch causes Perl to dump core after compiling your program.
740 You can then in theory take this core dump and turn it into an
741 executable file by using the undump program (not supplied). This
742 speeds startup at the expense of some disk space (which you can
743 minimize by stripping the executable). (Still, a "hello world"
744 executable comes out to about 200K on my machine.) If you want to
745 execute a portion of your program before dumping, use the dump()
746 operator instead. Note: availability of undump is platform
747 specific and may not be available for a specific port of Perl.
748
749 -U allows Perl to do unsafe operations. Currently the only "unsafe"
750 operations are attempting to unlink directories while running as
751 superuser and running setuid programs with fatal taint checks
752 turned into warnings. Note that warnings must be enabled along
753 with this option to actually generate the taint-check warnings.
754
755 -v prints the version and patchlevel of your perl executable.
756
757 -V prints summary of the major perl configuration values and the
758 current values of @INC.
759
760 -V:configvar
761 Prints to STDOUT the value of the named configuration variable(s),
762 with multiples when your "configvar" argument looks like a regex
763 (has non-letters). For example:
764
765 $ perl -V:libc
766 libc='/lib/libc-2.2.4.so';
767 $ perl -V:lib.
768 libs='-lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lc';
769 libc='/lib/libc-2.2.4.so';
770 $ perl -V:lib.*
771 libpth='/usr/local/lib /lib /usr/lib';
772 libs='-lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lc';
773 lib_ext='.a';
774 libc='/lib/libc-2.2.4.so';
775 libperl='libperl.a';
776 ....
777
778 Additionally, extra colons can be used to control formatting. A
779 trailing colon suppresses the linefeed and terminator ";",
780 allowing you to embed queries into shell commands. (mnemonic:
781 PATH separator ":".)
782
783 $ echo "compression-vars: " `perl -V:z.*: ` " are here !"
784 compression-vars: zcat='' zip='zip' are here !
785
786 A leading colon removes the "name=" part of the response, this
787 allows you to map to the name you need. (mnemonic: empty label)
788
789 $ echo "goodvfork="`./perl -Ilib -V::usevfork`
790 goodvfork=false;
791
792 Leading and trailing colons can be used together if you need
793 positional parameter values without the names. Note that in the
794 case below, the "PERL_API" params are returned in alphabetical
795 order.
796
797 $ echo building_on `perl -V::osname: -V::PERL_API_.*:` now
798 building_on 'linux' '5' '1' '9' now
799
800 -w prints warnings about dubious constructs, such as variable names
801 mentioned only once and scalar variables used before being set;
802 redefined subroutines; references to undefined filehandles;
803 filehandles opened read-only that you are attempting to write on;
804 values used as a number that don't look like numbers; using an
805 array as though it were a scalar; if your subroutines recurse more
806 than 100 deep; and innumerable other things.
807
808 This switch really just enables the global $^W variable; normally,
809 the lexically scoped "use warnings" pragma is preferred. You can
810 disable or promote into fatal errors specific warnings using
811 "__WARN__" hooks, as described in perlvar and "warn" in perlfunc.
812 See also perldiag and perltrap. A fine-grained warning facility
813 is also available if you want to manipulate entire classes of
814 warnings; see warnings or perllexwarn.
815
816 -W Enables all warnings regardless of "no warnings" or $^W. See
817 perllexwarn.
818
819 -X Disables all warnings regardless of "use warnings" or $^W. See
820 perllexwarn.
821
822 -x
823 -xdirectory
824 tells Perl that the program is embedded in a larger chunk of
825 unrelated text, such as in a mail message. Leading garbage will
826 be discarded until the first line that starts with "#!" and
827 contains the string "perl". Any meaningful switches on that line
828 will be applied.
829
830 All references to line numbers by the program (warnings, errors,
831 ...) will treat the "#!" line as the first line. Thus a warning
832 on the 2nd line of the program, which is on the 100th line in the
833 file will be reported as line 2, not as line 100. This can be
834 overridden by using the "#line" directive. (See "Plain Old
835 Comments (Not!)" in perlsyn)
836
837 If a directory name is specified, Perl will switch to that
838 directory before running the program. The -x switch controls only
839 the disposal of leading garbage. The program must be terminated
840 with "__END__" if there is trailing garbage to be ignored; the
841 program can process any or all of the trailing garbage via the
842 "DATA" filehandle if desired.
843
844 The directory, if specified, must appear immediately following the
845 -x with no intervening whitespace.
846
848 HOME Used if "chdir" has no argument.
849
850 LOGDIR Used if "chdir" has no argument and HOME is not set.
851
852 PATH Used in executing subprocesses, and in finding the program
853 if -S is used.
854
855 PERL5LIB A list of directories in which to look for Perl library
856 files before looking in the standard library and the
857 current directory. Any architecture-specific directories
858 under the specified locations are automatically included if
859 they exist, with this lookup done at interpreter startup
860 time.
861
862 If PERL5LIB is not defined, PERLLIB is used. Directories
863 are separated (like in PATH) by a colon on Unixish
864 platforms and by a semicolon on Windows (the proper path
865 separator being given by the command "perl -V:path_sep").
866
867 When running taint checks, either because the program was
868 running setuid or setgid, or the -T or -t switch was
869 specified, neither PERL5LIB nor PERLLIB is consulted. The
870 program should instead say:
871
872 use lib "/my/directory";
873
874 PERL5OPT Command-line options (switches). Switches in this variable
875 are treated as if they were on every Perl command line.
876 Only the -[CDIMUdmtwW] switches are allowed. When running
877 taint checks (either because the program was running setuid
878 or setgid, or because the -T or -t switch was used), this
879 variable is ignored. If PERL5OPT begins with - T, tainting
880 will be enabled and subsequent options ignored. If
881 PERL5OPT begins with -t, tainting will be enabled, a
882 writable dot removed from @INC, and subsequent options
883 honored.
884
885 PERLIO A space (or colon) separated list of PerlIO layers. If perl
886 is built to use PerlIO system for IO (the default) these
887 layers affect Perl's IO.
888
889 It is conventional to start layer names with a colon (for
890 example, ":perlio") to emphasize their similarity to
891 variable "attributes". But the code that parses layer
892 specification strings, which is also used to decode the
893 PERLIO environment variable, treats the colon as a
894 separator.
895
896 An unset or empty PERLIO is equivalent to the default set
897 of layers for your platform; for example, ":unix:perlio" on
898 Unix-like systems and ":unix:crlf" on Windows and other
899 DOS-like systems.
900
901 The list becomes the default for all Perl's IO.
902 Consequently only built-in layers can appear in this list,
903 as external layers (such as ":encoding()") need IO in
904 order to load them!. See "open pragma" for how to add
905 external encodings as defaults.
906
907 Layers it makes sense to include in the PERLIO environment
908 variable are briefly summarized below. For more details see
909 PerlIO.
910
911 :bytes A pseudolayer that turns the ":utf8" flag off for
912 the layer below; unlikely to be useful on its own
913 in the global PERLIO environment variable. You
914 perhaps were thinking of ":crlf:bytes" or
915 ":perlio:bytes".
916
917 :crlf A layer which does CRLF to "\n" translation
918 distinguishing "text" and "binary" files in the
919 manner of MS-DOS and similar operating systems.
920 (It currently does not mimic MS-DOS as far as
921 treating of Control-Z as being an end-of-file
922 marker.)
923
924 :mmap A layer that implements "reading" of files by using
925 mmap(2) to make an entire file appear in the
926 process's address space, and then using that as
927 PerlIO's "buffer".
928
929 :perlio This is a re-implementation of stdio-like buffering
930 written as a PerlIO layer. As such it will call
931 whatever layer is below it for its operations,
932 typically ":unix".
933
934 :pop An experimental pseudolayer that removes the
935 topmost layer. Use with the same care as is
936 reserved for nitroglycerine.
937
938 :raw A pseudolayer that manipulates other layers.
939 Applying the ":raw" layer is equivalent to calling
940 "binmode($fh)". It makes the stream pass each byte
941 as-is without translation. In particular, both
942 CRLF translation and intuiting ":utf8" from the
943 locale are disabled.
944
945 Unlike in earlier versions of Perl, ":raw" is not
946 just the inverse of ":crlf": other layers which
947 would affect the binary nature of the stream are
948 also removed or disabled.
949
950 :stdio This layer provides a PerlIO interface by wrapping
951 system's ANSI C "stdio" library calls. The layer
952 provides both buffering and IO. Note that the
953 ":stdio" layer does not do CRLF translation even if
954 that is the platform's normal behaviour. You will
955 need a ":crlf" layer above it to do that.
956
957 :unix Low-level layer that calls "read", "write",
958 "lseek", etc.
959
960 :utf8 A pseudolayer that enables a flag in the layer
961 below to tell Perl that output should be in utf8
962 and that input should be regarded as already in
963 valid utf8 form. WARNING: It does not check for
964 validity and as such should be handled with extreme
965 caution for input, because security violations can
966 occur with non-shortest UTF-8 encodings, etc.
967 Generally ":encoding(utf8)" is the best option when
968 reading UTF-8 encoded data.
969
970 :win32 On Win32 platforms this experimental layer uses
971 native "handle" IO rather than a Unix-like numeric
972 file descriptor layer. Known to be buggy in this
973 release (5.14).
974
975 The default set of layers should give acceptable results on
976 all platforms
977
978 For Unix platforms that will be the equivalent of "unix
979 perlio" or "stdio". Configure is set up to prefer the
980 "stdio" implementation if the system's library provides for
981 fast access to the buffer; otherwise, it uses the "unix
982 perlio" implementation.
983
984 On Win32 the default in this release (5.14) is "unix crlf".
985 Win32's "stdio" has a number of bugs/mis-features for Perl
986 IO which are somewhat depending on the version and vendor
987 of the C compiler. Using our own "crlf" layer as the buffer
988 avoids those issues and makes things more uniform. The
989 "crlf" layer provides CRLF conversion as well as buffering.
990
991 This release (5.14) uses "unix" as the bottom layer on
992 Win32, and so still uses the C compiler's numeric file
993 descriptor routines. There is an experimental native
994 "win32" layer, which is expected to be enhanced and should
995 eventually become the default under Win32.
996
997 The PERLIO environment variable is completely ignored when
998 Perl is run in taint mode.
999
1000 PERLIO_DEBUG
1001 If set to the name of a file or device, certain operations
1002 of PerlIO subsystem will be logged to that file, which is
1003 opened in append mode Typical uses are in Unix:
1004
1005 % env PERLIO_DEBUG=/dev/tty perl script ...
1006
1007 and under Win32, the approximately equivalent:
1008
1009 > set PERLIO_DEBUG=CON
1010 perl script ...
1011
1012 This functionality is disabled for setuid scripts and for
1013 scripts run with -T.
1014
1015 PERLLIB A list of directories in which to look for Perl library
1016 files before looking in the standard library and the
1017 current directory. If PERL5LIB is defined, PERLLIB is not
1018 used.
1019
1020 The PERLLIB environment variable is completely ignored when
1021 Perl is run in taint mode.
1022
1023 PERL5DB The command used to load the debugger code. The default
1024 is:
1025
1026 BEGIN { require "perl5db.pl" }
1027
1028 The PERL5DB environment variable is only used when Perl is
1029 started with a bare -d switch.
1030
1031 PERL5DB_THREADED
1032 If set to a true value, indicates to the debugger that the
1033 code being debugged uses threads.
1034
1035 PERL5SHELL (specific to the Win32 port)
1036 On Win32 ports only, may be set to an alternative shell
1037 that Perl must use internally for executing "backtick"
1038 commands or system(). Default is "cmd.exe /x/d/c" on
1039 WindowsNT and "command.com /c" on Windows95. The value is
1040 considered space-separated. Precede any character that
1041 needs to be protected, like a space or backslash, with
1042 another backslash.
1043
1044 Note that Perl doesn't use COMSPEC for this purpose because
1045 COMSPEC has a high degree of variability among users,
1046 leading to portability concerns. Besides, Perl can use a
1047 shell that may not be fit for interactive use, and setting
1048 COMSPEC to such a shell may interfere with the proper
1049 functioning of other programs (which usually look in
1050 COMSPEC to find a shell fit for interactive use).
1051
1052 Before Perl 5.10.0 and 5.8.8, PERL5SHELL was not taint
1053 checked when running external commands. It is recommended
1054 that you explicitly set (or delete) $ENV{PERL5SHELL} when
1055 running in taint mode under Windows.
1056
1057 PERL_ALLOW_NON_IFS_LSP (specific to the Win32 port)
1058 Set to 1 to allow the use of non-IFS compatible LSPs
1059 (Layered Service Providers). Perl normally searches for an
1060 IFS-compatible LSP because this is required for its
1061 emulation of Windows sockets as real filehandles. However,
1062 this may cause problems if you have a firewall such as
1063 McAfee Guardian, which requires that all applications use
1064 its LSP but which is not IFS-compatible, because clearly
1065 Perl will normally avoid using such an LSP.
1066
1067 Setting this environment variable to 1 means that Perl will
1068 simply use the first suitable LSP enumerated in the
1069 catalog, which keeps McAfee Guardian happy--and in that
1070 particular case Perl still works too because McAfee
1071 Guardian's LSP actually plays other games which allow
1072 applications requiring IFS compatibility to work.
1073
1074 PERL_DEBUG_MSTATS
1075 Relevant only if Perl is compiled with the "malloc"
1076 included with the Perl distribution; that is, if "perl
1077 -V:d_mymalloc" is "define".
1078
1079 If set, this dumps out memory statistics after execution.
1080 If set to an integer greater than one, also dumps out
1081 memory statistics after compilation.
1082
1083 PERL_DESTRUCT_LEVEL
1084 Relevant only if your Perl executable was built with
1085 -DDEBUGGING, this controls the behaviour of global
1086 destruction of objects and other references. See
1087 "PERL_DESTRUCT_LEVEL" in perlhacktips for more information.
1088
1089 PERL_DL_NONLAZY
1090 Set to "1" to have Perl resolve all undefined symbols when
1091 it loads a dynamic library. The default behaviour is to
1092 resolve symbols when they are used. Setting this variable
1093 is useful during testing of extensions, as it ensures that
1094 you get an error on misspelled function names even if the
1095 test suite doesn't call them.
1096
1097 PERL_ENCODING
1098 If using the "use encoding" pragma without an explicit
1099 encoding name, the PERL_ENCODING environment variable is
1100 consulted for an encoding name.
1101
1102 PERL_HASH_SEED
1103 (Since Perl 5.8.1.) Used to randomize Perl's internal hash
1104 function. To emulate the pre-5.8.1 behaviour, set to an
1105 integer; "0" means exactly the same order as in 5.8.0.
1106 "Pre-5.8.1" means, among other things, that hash keys will
1107 always have the same ordering between different runs of
1108 Perl.
1109
1110 Most hashes by default return elements in the same order as
1111 in Perl 5.8.0. On a hash by hash basis, if pathological
1112 data is detected during a hash key insertion, then that
1113 hash will switch to an alternative random hash seed.
1114
1115 The default behaviour is to randomize unless the
1116 PERL_HASH_SEED is set. If Perl has been compiled with
1117 -DUSE_HASH_SEED_EXPLICIT, the default behaviour is not to
1118 randomize unless the PERL_HASH_SEED is set.
1119
1120 If PERL_HASH_SEED is unset or set to a non-numeric string,
1121 Perl uses the pseudorandom seed supplied by the operating
1122 system and libraries.
1123
1124 PLEASE NOTE: The hash seed is sensitive information. Hashes
1125 are randomized to protect against local and remote attacks
1126 against Perl code. By manually setting a seed, this
1127 protection may be partially or completely lost.
1128
1129 See "Algorithmic Complexity Attacks" in perlsec and
1130 "PERL_HASH_SEED_DEBUG" for more information.
1131
1132 PERL_HASH_SEED_DEBUG
1133 (Since Perl 5.8.1.) Set to "1" to display (to STDERR) the
1134 value of the hash seed at the beginning of execution.
1135 This, combined with "PERL_HASH_SEED" is intended to aid in
1136 debugging nondeterministic behaviour caused by hash
1137 randomization.
1138
1139 Note that the hash seed is sensitive information: by
1140 knowing it, one can craft a denial-of-service attack
1141 against Perl code, even remotely; see "Algorithmic
1142 Complexity Attacks" in perlsec for more information. Do
1143 not disclose the hash seed to people who don't need to know
1144 it. See also hash_seed() in Hash::Util.
1145
1146 PERL_MEM_LOG
1147 If your Perl was configured with -Accflags=-DPERL_MEM_LOG,
1148 setting the environment variable "PERL_MEM_LOG" enables
1149 logging debug messages. The value has the form
1150 "<number>[m][s][t]", where "number" is the file descriptor
1151 number you want to write to (2 is default), and the
1152 combination of letters specifies that you want information
1153 about (m)emory and/or (s)v, optionally with (t)imestamps.
1154 For example, "PERL_MEM_LOG=1mst" logs all information to
1155 stdout. You can write to other opened file descriptors in a
1156 variety of ways:
1157
1158 $ 3>foo3 PERL_MEM_LOG=3m perl ...
1159
1160 PERL_ROOT (specific to the VMS port)
1161 A translation-concealed rooted logical name that contains
1162 Perl and the logical device for the @INC path on VMS only.
1163 Other logical names that affect Perl on VMS include
1164 PERLSHR, PERL_ENV_TABLES, and SYS$TIMEZONE_DIFFERENTIAL,
1165 but are optional and discussed further in perlvms and in
1166 README.vms in the Perl source distribution.
1167
1168 PERL_SIGNALS
1169 Available in Perls 5.8.1 and later. If set to "unsafe",
1170 the pre-Perl-5.8.0 signal behaviour (which is immediate but
1171 unsafe) is restored. If set to "safe", then safe (but
1172 deferred) signals are used. See "Deferred Signals (Safe
1173 Signals)" in perlipc.
1174
1175 PERL_UNICODE
1176 Equivalent to the -C command-line switch. Note that this
1177 is not a boolean variable. Setting this to "1" is not the
1178 right way to "enable Unicode" (whatever that would mean).
1179 You can use "0" to "disable Unicode", though (or
1180 alternatively unset PERL_UNICODE in your shell before
1181 starting Perl). See the description of the -C switch for
1182 more information.
1183
1184 SYS$LOGIN (specific to the VMS port)
1185 Used if chdir has no argument and HOME and LOGDIR are not
1186 set.
1187
1188 Perl also has environment variables that control how Perl handles data
1189 specific to particular natural languages; see perllocale.
1190
1191 Perl and its various modules and components, including its test
1192 frameworks, may sometimes make use of certain other environment
1193 variables. Some of these are specific to a particular platform.
1194 Please consult the appropriate module documentation and any
1195 documentation for your platform (like perlsolaris, perllinux,
1196 perlmacosx, perlwin32, etc) for variables peculiar to those specific
1197 situations.
1198
1199 Perl makes all environment variables available to the program being
1200 executed, and passes these along to any child processes it starts.
1201 However, programs running setuid would do well to execute the following
1202 lines before doing anything else, just to keep people honest:
1203
1204 $ENV{PATH} = "/bin:/usr/bin"; # or whatever you need
1205 $ENV{SHELL} = "/bin/sh" if exists $ENV{SHELL};
1206 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
1207
1208
1209
1210perl v5.16.3 2013-03-04 PERLRUN(1)