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