1PERLRUN(1)             Perl Programmers Reference Guide             PERLRUN(1)
2
3
4

NAME

6       perlrun - how to execute the Perl interpreter
7

SYNOPSIS

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] ]      [ -P ]      [ -R ]      [ -S ]
14            [ -x[dir] ]      [ -i[extension] ]      [ -e 'com‐
15       mand' ] [ -- ] [ programfile ] [ argument ]...
16

DESCRIPTION

18       The normal way to run a Perl program is by making it directly exe‐
19       cutable, or else by passing the name of the source file as an argument
20       on the command line.  (An interactive Perl environment is also possi‐
21       ble--see perldebug for details on how to do that.)  Upon startup, Perl
22       looks for your program in one of the following places:
23
24       1.  Specified line by line via -e switches on the command line.
25
26       2.  Contained in the file specified by the first filename on the com‐
27           mand 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 pro‐
32           gram 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 pro‐
39       gram 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 pro‐
55       gram.  And a partial -I switch could also cause odd results.
56
57       Some switches do care if they are processed twice, for instance combi‐
58       nations of -l and -0.  Either put all the switches after the 32-charac‐
59       ter boundary (if applicable), or replace the use of -0digits by "BEGIN{
60       $/ = "\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 -- # -*- perl -*- -p
67           eval 'exec perl -wS $0 ${1+"$@"}'
68               if $running_under_some_shell;
69
70       to let Perl see the -p switch.
71
72       A similar trick involves the env program, if you have it.
73
74           #!/usr/bin/env perl
75
76       The examples above use a relative path to the perl interpreter, getting
77       whatever version is first in the user's path.  If you want a specific
78       version of Perl, say, perl5.005_57, you should place that directly in
79       the #! line's path.
80
81       If the #! line does not contain the word "perl", the program named
82       after the #! is executed instead of the Perl interpreter.  This is
83       slightly bizarre, but it helps people on machines that don't do #!,
84       because they can tell a program that their SHELL is /usr/bin/perl, and
85       Perl will then dispatch the program to the correct interpreter for
86       them.
87
88       After locating your program, Perl compiles the entire program to an
89       internal form.  If there are any compilation errors, execution of the
90       program is not attempted.  (This is unlike the typical shell script,
91       which might run part-way through before finding a syntax error.)
92
93       If the program is syntactically correct, it is executed.  If the pro‐
94       gram runs off the end without hitting an exit() or die() operator, an
95       implicit exit(0) is provided to indicate successful completion.
96
97       #! and quoting on non-Unix systems
98
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 "ALTER‐
111           NATE_SHEBANG" (see the dosish.h file in the source distribution for
112           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 (includ‐
118           ing building from the sources), you may have to modify the Registry
119           yourself.  Note that this means you can no longer tell the differ‐
120           ence between an executable Perl program and a Perl library file.
121
122       Macintosh
123           Under "Classic" MacOS, a perl program will have the appropriate
124           Creator and Type, so that double-clicking them will invoke the
125           MacPerl application.  Under Mac OS X, clickable apps can be made
126           from any "#!" script using Wil Sanchez' DropScript utility:
127           http://www.wsanchez.net/software/ .
128
129       VMS Put
130
131               $ perl -mysw 'f$env("procedure")' 'p1' 'p2' 'p3' 'p4' 'p5' 'p6' 'p7' 'p8' !
132               $ exit++ + ++$status != 0 and $exit = $status = undef;
133
134           at the top of your program, where -mysw are any command line
135           switches you want to pass to Perl.  You can now invoke the program
136           directly, by saying "perl program", or as a DCL procedure, by say‐
137           ing @program (or implicitly via DCL$PATH by just using the name of
138           the program).
139
140           This incantation is a bit much to remember, but Perl will display
141           it for you if you say "perl "-V:startperl"".
142
143       Command-interpreters on non-Unix systems have rather different ideas on
144       quoting than Unix shells.  You'll need to learn the special characters
145       in your command-interpreter ("*", "\" and """ are common) and how to
146       protect whitespace and these characters to run one-liners (see -e
147       below).
148
149       On some systems, you may have to change single-quotes to double ones,
150       which you must not do on Unix or Plan 9 systems.  You might also have
151       to change a single % to a %%.
152
153       For example:
154
155           # Unix
156           perl -e 'print "Hello world\n"'
157
158           # MS-DOS, etc.
159           perl -e "print \"Hello world\n\""
160
161           # Macintosh
162           print "Hello world\n"
163            (then Run "Myscript" or Shift-Command-R)
164
165           # VMS
166           perl -e "print ""Hello world\n"""
167
168       The problem is that none of this is reliable: it depends on the command
169       and it is entirely possible neither works.  If 4DOS were the command
170       shell, this would probably work better:
171
172           perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>""
173
174       CMD.EXE in Windows NT slipped a lot of standard Unix functionality in
175       when nobody was looking, but just try to find documentation for its
176       quoting rules.
177
178       Under the Macintosh, it depends which environment you are using.  The
179       MacPerl shell, or MPW, is much like Unix shells in its support for sev‐
180       eral quoting variants, except that it makes free use of the Macintosh's
181       non-ASCII characters as control characters.
182
183       There is no general solution to all of this.  It's just a mess.
184
185       Location of Perl
186
187       It may seem obvious to say, but Perl is useful only when users can eas‐
188       ily find it.  When possible, it's good for both /usr/bin/perl and
189       /usr/local/bin/perl to be symlinks to the actual binary.  If that can't
190       be done, system administrators are strongly encouraged to put (symlinks
191       to) perl and its accompanying utilities into a directory typically
192       found along a user's PATH, or in some other obvious and convenient
193       place.
194
195       In this documentation, "#!/usr/bin/perl" on the first line of the pro‐
196       gram will stand in for whatever method works on your system.  You are
197       advised to use a specific path if you care about a specific version.
198
199           #!/usr/local/bin/perl5.00554
200
201       or if you just want to be running at least version, place a statement
202       like this at the top of your program:
203
204           use 5.005_54;
205
206       Command Switches
207
208       As with all standard commands, a single-character switch may be clus‐
209       tered with the following switch, if any.
210
211           #!/usr/bin/perl -spi.orig   # same as -s -p -i.orig
212
213       Switches include:
214
215       -0[octal/hexadecimal]
216            specifies the input record separator ($/) as an octal or hexadeci‐
217            mal number.  If there are no digits, the null character is the
218            separator.  Other switches may precede or follow the digits.  For
219            example, if you have a version of find which can print filenames
220            terminated by the null character, you can say this:
221
222                find . -name '*.orig' -print0 ⎪ perl -n0e unlink
223
224            The special value 00 will cause Perl to slurp files in paragraph
225            mode.  The value 0777 will cause Perl to slurp files whole because
226            there is no legal byte with that value.
227
228            If you want to specify any Unicode character, use the hexadecimal
229            format: "-0xHHH...", where the "H" are valid hexadecimal digits.
230            (This means that you cannot use the "-x" with a directory name
231            that consists of hexadecimal digits.)
232
233       -a   turns on autosplit mode when used with a -n or -p.  An implicit
234            split command to the @F array is done as the first thing inside
235            the implicit while loop produced by the -n or -p.
236
237                perl -ane 'print pop(@F), "\n";'
238
239            is equivalent to
240
241                while (<>) {
242                    @F = split(' ');
243                    print pop(@F), "\n";
244                }
245
246            An alternate delimiter may be specified using -F.
247
248       -C [number/list]
249            The "-C" flag controls some Unicode of the Perl Unicode features.
250
251            As of 5.8.1, the "-C" can be followed either by a number or a list
252            of option letters.  The letters, their numeric values, and effects
253            are as follows; listing the letters is equal to summing the num‐
254            bers.
255
256                I     1    STDIN is assumed to be in UTF-8
257                O     2    STDOUT will be in UTF-8
258                E     4    STDERR will be in UTF-8
259                S     7    I + O + E
260                i     8    UTF-8 is the default PerlIO layer for input streams
261                o    16    UTF-8 is the default PerlIO layer for output streams
262                D    24    i + o
263                A    32    the @ARGV elements are expected to be strings encoded in UTF-8
264                L    64    normally the "IOEioA" are unconditional,
265                           the L makes them conditional on the locale environment
266                           variables (the LC_ALL, LC_TYPE, and LANG, in the order
267                           of decreasing precedence) -- if the variables indicate
268                           UTF-8, then the selected "IOEioA" are in effect
269
270            For example, "-COE" and "-C6" will both turn on UTF-8-ness on both
271            STDOUT and STDERR.  Repeating letters is just redundant, not cumu‐
272            lative nor toggling.
273
274            The "io" options mean that any subsequent open() (or similar I/O
275            operations) will have the ":utf8" PerlIO layer implicitly applied
276            to them, in other words, UTF-8 is expected from any input stream,
277            and UTF-8 is produced to any output stream.  This is just the
278            default, with explicit layers in open() and with binmode() one can
279            manipulate streams as usual.
280
281            "-C" on its own (not followed by any number or option list), or
282            the empty string "" for the "PERL_UNICODE" environment variable,
283            has the same effect as "-CSDL".  In other words, the standard I/O
284            handles and the default "open()" layer are UTF-8-fied but only if
285            the locale environment variables indicate a UTF-8 locale.  This
286            behaviour follows the implicit (and problematic) UTF-8 behaviour
287            of Perl 5.8.0.
288
289            You can use "-C0" (or "0" for "PERL_UNICODE") to explicitly dis‐
290            able all the above Unicode features.
291
292            The read-only magic variable "${^UNICODE}" reflects the numeric
293            value of this setting.  This is variable is set during Perl
294            startup and is thereafter read-only.  If you want runtime effects,
295            use the three-arg open() (see "open" in perlfunc), the two-arg
296            binmode() (see "binmode" in perlfunc), and the "open" pragma (see
297            open).
298
299            (In Perls earlier than 5.8.1 the "-C" switch was a Win32-only
300            switch that enabled the use of Unicode-aware "wide system call"
301            Win32 APIs.  This feature was practically unused, however, and the
302            command line switch was therefore "recycled".)
303
304       -c   causes Perl to check the syntax of the program and then exit with‐
305            out executing it.  Actually, it will execute "BEGIN", "CHECK", and
306            "use" blocks, because these are considered as occurring outside
307            the execution of your program.  "INIT" and "END" blocks, however,
308            will be skipped.
309
310       -d
311       -dt  runs the program under the Perl debugger.  See perldebug.  If t is
312            specified, it indicates to the debugger that threads will be used
313            in the code being debugged.
314
315       -d:foo[=bar,baz]
316       -dt:foo[=bar,baz]
317            runs the program under the control of a debugging, profiling, or
318            tracing module installed as Devel::foo. E.g., -d:DProf executes
319            the program using the Devel::DProf profiler.  As with the -M flag,
320            options may be passed to the Devel::foo package where they will be
321            received and interpreted by the Devel::foo::import routine.  The
322            comma-separated list of options must follow a "=" character.  If t
323            is specified, it indicates to the debugger that threads will be
324            used in the code 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
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, preprocessor command for -P, source file input state
344                  128  m  Memory 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     (Obsolete, previously used for LEAKTEST)
350                 8192  H  Hash dump -- usurps values()
351                16384  X  Scratchpad allocation
352                32768  D  Cleaning up
353                65536  S  Thread synchronization
354               131072  T  Tokenising
355               262144  R  Include reference counts of dumped variables (eg when using -Ds)
356               524288  J  Do not s,t,P-debug (Jump over) opcodes within package DB
357              1048576  v  Verbose: use in conjunction with other flags
358              8388608  q  quiet - currently only suppresses the "EXECUTING" message
359
360            All these flags require -DDEBUGGING when you compile the Perl exe‐
361            cutable (but see Devel::Peek, re which may change this).  See the
362            INSTALL file in the Perl source distribution for how to do this.
363            This flag is automatically set if you include -g option when "Con‐
364            figure" asks you about optimizer/debugger flags.
365
366            If you're just trying to get a print out of each line of Perl code
367            as it executes, the way that "sh -x" provides for shell scripts,
368            you can't use Perl's -D switch.  Instead do this
369
370              # If you have "env" utility
371              env PERLDB_OPTS="NonStop=1 AutoTrace=1 frame=2" perl -dS program
372
373              # Bourne shell syntax
374              $ PERLDB_OPTS="NonStop=1 AutoTrace=1 frame=2" perl -dS program
375
376              # csh syntax
377              % (setenv PERLDB_OPTS "NonStop=1 AutoTrace=1 frame=2"; perl -dS program)
378
379            See perldebug for details and variations.
380
381       -e commandline
382            may be used to enter one line of program.  If -e is given, Perl
383            will not look for a filename in the argument list.  Multiple -e
384            commands may be given to build up a multi-line script.  Make sure
385            to use semicolons where you would in a normal program.
386
387       -f   Disable executing $Config{sitelib}/sitecustomize.pl at startup.
388
389            Perl can be built so that it by default will try to execute $Con‐
390            fig{sitelib}/sitecustomize.pl at startup.  This is a hook that
391            allows the sysadmin to customize how perl behaves.  It can for
392            instance be used to add entries to the @INC array to make perl
393            find modules in non-standard locations.
394
395       -Fpattern
396            specifies the pattern to split on if -a is also in effect.  The
397            pattern may be surrounded by "//", "", or '', otherwise it will be
398            put in single quotes. You can't use literal whitespace in the pat‐
399            tern.
400
401       -h   prints a summary of the options.
402
403       -i[extension]
404            specifies that files processed by the "<>" construct are to be
405            edited in-place.  It does this by renaming the input file, opening
406            the output file by the original name, and selecting that output
407            file as the default for print() statements.  The extension, if
408            supplied, is used to modify the name of the old file to make a
409            backup copy, following these rules:
410
411            If no extension is supplied, no backup is made and the current
412            file is overwritten.
413
414            If the extension doesn't contain a "*", then it is appended to the
415            end of the current filename as a suffix.  If the extension does
416            contain one or more "*" characters, then each "*" is replaced with
417            the current filename.  In Perl terms, you could think of this as:
418
419                ($backup = $extension) =~ s/\*/$file_name/g;
420
421            This allows you to add a prefix to the backup file, instead of (or
422            in addition to) a suffix:
423
424                $ perl -pi'orig_*' -e 's/bar/baz/' fileA    # backup to 'orig_fileA'
425
426            Or even to place backup copies of the original files into another
427            directory (provided the directory already exists):
428
429                $ perl -pi'old/*.orig' -e 's/bar/baz/' fileA # backup to 'old/fileA.orig'
430
431            These sets of one-liners are equivalent:
432
433                $ perl -pi -e 's/bar/baz/' fileA            # overwrite current file
434                $ perl -pi'*' -e 's/bar/baz/' fileA         # overwrite current file
435
436                $ perl -pi'.orig' -e 's/bar/baz/' fileA     # backup to 'fileA.orig'
437                $ perl -pi'*.orig' -e 's/bar/baz/' fileA    # backup to 'fileA.orig'
438
439            From the shell, saying
440
441                $ perl -p -i.orig -e "s/foo/bar/; ... "
442
443            is the same as using the program:
444
445                #!/usr/bin/perl -pi.orig
446                s/foo/bar/;
447
448            which is equivalent to
449
450                #!/usr/bin/perl
451                $extension = '.orig';
452                LINE: while (<>) {
453                    if ($ARGV ne $oldargv) {
454                        if ($extension !~ /\*/) {
455                            $backup = $ARGV . $extension;
456                        }
457                        else {
458                            ($backup = $extension) =~ s/\*/$ARGV/g;
459                        }
460                        rename($ARGV, $backup);
461                        open(ARGVOUT, ">$ARGV");
462                        select(ARGVOUT);
463                        $oldargv = $ARGV;
464                    }
465                    s/foo/bar/;
466                }
467                continue {
468                    print;  # this prints to original filename
469                }
470                select(STDOUT);
471
472            except that the -i form doesn't need to compare $ARGV to $oldargv
473            to know when the filename has changed.  It does, however, use
474            ARGVOUT for the selected filehandle.  Note that STDOUT is restored
475            as the default output filehandle after the loop.
476
477            As shown above, Perl creates the backup file whether or not any
478            output is actually changed.  So this is just a fancy way to copy
479            files:
480
481                $ perl -p -i'/some/file/path/*' -e 1 file1 file2 file3...
482            or
483                $ perl -p -i'.orig' -e 1 file1 file2 file3...
484
485            You can use "eof" without parentheses to locate the end of each
486            input file, in case you want to append to each file, or reset line
487            numbering (see example in "eof" in perlfunc).
488
489            If, for a given file, Perl is unable to create the backup file as
490            specified in the extension then it will skip that file and con‐
491            tinue on with the next one (if it exists).
492
493            For a discussion of issues surrounding file permissions and -i,
494            see "Why does Perl let me delete read-only files? Why does -i
495            clobber protected files? Isn't this a bug in Perl?" in perlfaq5.
496
497            You cannot use -i to create directories or to strip extensions
498            from files.
499
500            Perl does not expand "~" in filenames, which is good, since some
501            folks use it for their backup files:
502
503                $ perl -pi~ -e 's/foo/bar/' file1 file2 file3...
504
505            Note that because -i renames or deletes the original file before
506            creating a new file of the same name, UNIX-style soft and hard
507            links will not be preserved.
508
509            Finally, the -i switch does not impede execution when no files are
510            given on the command line.  In this case, no backup is made (the
511            original file cannot, of course, be determined) and processing
512            proceeds from STDIN to STDOUT as might be expected.
513
514       -Idirectory
515            Directories specified by -I are prepended to the search path for
516            modules (@INC), and also tells the C preprocessor where to search
517            for include files.  The C preprocessor is invoked with -P; by
518            default it searches /usr/include and /usr/lib/perl.
519
520       -l[octnum]
521            enables automatic line-ending processing.  It has two separate
522            effects.  First, it automatically chomps $/ (the input record sep‐
523            arator) when used with -n or -p.  Second, it assigns "$\" (the
524            output record separator) to have the value of octnum so that any
525            print statements will have that separator added back on.  If oct‐
526            num is omitted, sets "$\" to the current value of $/.  For
527            instance, to trim lines to 80 columns:
528
529                perl -lpe 'substr($_, 80) = ""'
530
531            Note that the assignment "$\ = $/" is done when the switch is pro‐
532            cessed, so the input record separator can be different than the
533            output record separator if the -l switch is followed by a -0
534            switch:
535
536                gnufind / -print0 ⎪ perl -ln0e 'print "found $_" if -p'
537
538            This sets "$\" to newline and then sets $/ to the null character.
539
540       -m[-]module
541       -M[-]module
542       -M[-]'module ...'
543       -[mM][-]module=arg[,arg]...
544            -mmodule executes "use" module "();" before executing your pro‐
545            gram.
546
547            -Mmodule executes "use" module ";" before executing your program.
548            You can use quotes to add extra code after the module name, e.g.,
549            '-Mmodule qw(foo bar)'.
550
551            If the first character after the -M or -m is a dash ("-") then the
552            'use' is replaced with 'no'.
553
554            A little builtin syntactic sugar means you can also say -mmod‐
555            ule=foo,bar or -Mmodule=foo,bar as a shortcut for '-Mmodule qw(foo
556            bar)'.  This avoids the need to use quotes when importing symbols.
557            The actual code generated by -Mmodule=foo,bar is "use module
558            split(/,/,q{foo,bar})".  Note that the "=" form removes the dis‐
559            tinction between -m and -M.
560
561            A consequence of this is that -MFoo=number never does a version
562            check (unless "Foo::import()" itself is set up to do a version
563            check, which could happen for example if Foo inherits from
564            Exporter.)
565
566       -n   causes Perl to assume the following loop around your program,
567            which makes it iterate over filename arguments somewhat like sed
568            -n or awk:
569
570              LINE:
571                while (<>) {
572                    ...             # your program goes here
573                }
574
575            Note that the lines are not printed by default.  See -p to have
576            lines printed.  If a file named by an argument cannot be opened
577            for some reason, Perl warns you about it and moves on to the next
578            file.
579
580            Here is an efficient way to delete all files that haven't been
581            modified for at least a week:
582
583                find . -mtime +7 -print ⎪ perl -nle unlink
584
585            This is faster than using the -exec switch of find because you
586            don't have to start a process on every filename found.  It does
587            suffer from the bug of mishandling newlines in pathnames, which
588            you can fix if you follow the example under -0.
589
590            "BEGIN" and "END" blocks may be used to capture control before or
591            after the implicit program loop, just as in awk.
592
593       -p   causes Perl to assume the following loop around your program,
594            which makes it iterate over filename arguments somewhat like sed:
595
596              LINE:
597                while (<>) {
598                    ...             # your program goes here
599                } continue {
600                    print or die "-p destination: $!\n";
601                }
602
603            If a file named by an argument cannot be opened for some reason,
604            Perl warns you about it, and moves on to the next file.  Note that
605            the lines are printed automatically.  An error occurring during
606            printing is treated as fatal.  To suppress printing use the -n
607            switch.  A -p overrides a -n switch.
608
609            "BEGIN" and "END" blocks may be used to capture control before or
610            after the implicit loop, just as in awk.
611
612       -P   NOTE: Use of -P is strongly discouraged because of its inherent
613            problems, including poor portability.
614
615            This option causes your program to be run through the C preproces‐
616            sor before compilation by Perl.  Because both comments and cpp
617            directives begin with the # character, you should avoid starting
618            comments with any words recognized by the C preprocessor such as
619            "if", "else", or "define".
620
621            If you're considering using "-P", you might also want to look at
622            the Filter::cpp module from CPAN.
623
624            The problems of -P include, but are not limited to:
625
626            *         The "#!" line is stripped, so any switches there don't
627                      apply.
628
629            *         A "-P" on a "#!" line doesn't work.
630
631            *         All lines that begin with (whitespace and) a "#" but do
632                      not look like cpp commands, are stripped, including any‐
633                      thing inside Perl strings, regular expressions, and
634                      here-docs .
635
636            *         In some platforms the C preprocessor knows too much: it
637                      knows about the C++ -style until-end-of-line comments
638                      starting with "//".  This will cause problems with com‐
639                      mon Perl constructs like
640
641                          s/foo//;
642
643                      because after -P this will became illegal code
644
645                          s/foo
646
647                      The workaround is to use some other quoting separator
648                      than "/", like for example "!":
649
650                          s!foo!!;
651
652            *         It requires not only a working C preprocessor but also a
653                      working sed.  If not on UNIX, you are probably out of
654                      luck on this.
655
656            *         Script line numbers are not preserved.
657
658            *         The "-x" does not work with "-P".
659
660       -s   enables rudimentary switch parsing for switches on the command
661            line after the program name but before any filename arguments (or
662            before an argument of --).  Any switch found there is removed from
663            @ARGV and sets the corresponding variable in the Perl program.
664            The following program prints "1" if the program is invoked with a
665            -xyz switch, and "abc" if it is invoked with -xyz=abc.
666
667                #!/usr/bin/perl -s
668                if ($xyz) { print "$xyz\n" }
669
670            Do note that a switch like --help creates the variable ${-help},
671            which is not compliant with "strict refs".  Also, when using this
672            option on a script with warnings enabled you may get a lot of spu‐
673            rious "used only once" warnings.
674
675       -S   makes Perl use the PATH environment variable to search for the
676            program (unless the name of the program contains directory separa‐
677            tors).
678
679            On some platforms, this also makes Perl append suffixes to the
680            filename while searching for it.  For example, on Win32 platforms,
681            the ".bat" and ".cmd" suffixes are appended if a lookup for the
682            original name fails, and if the name does not already end in one
683            of those suffixes.  If your Perl was compiled with DEBUGGING
684            turned on, using the -Dp switch to Perl shows how the search pro‐
685            gresses.
686
687            Typically this is used to emulate #! startup on platforms that
688            don't support #!.  Its also convenient when debugging a script
689            that uses #!, and is thus normally found by the shell's $PATH
690            search mechanism.
691
692            This example works on many platforms that have a shell compatible
693            with Bourne shell:
694
695                #!/usr/bin/perl
696                eval 'exec /usr/bin/perl -wS $0 ${1+"$@"}'
697                        if $running_under_some_shell;
698
699            The system ignores the first line and feeds the program to
700            /bin/sh, which proceeds to try to execute the Perl program as a
701            shell script.  The shell executes the second line as a normal
702            shell command, and thus starts up the Perl interpreter.  On some
703            systems $0 doesn't always contain the full pathname, so the -S
704            tells Perl to search for the program if necessary.  After Perl
705            locates the program, it parses the lines and ignores them because
706            the variable $running_under_some_shell is never true.  If the pro‐
707            gram will be interpreted by csh, you will need to replace
708            "${1+"$@"}" with $*, even though that doesn't understand embedded
709            spaces (and such) in the argument list.  To start up sh rather
710            than csh, some systems may have to replace the #! line with a line
711            containing just a colon, which will be politely ignored by Perl.
712            Other systems can't control that, and need a totally devious con‐
713            struct that will work under any of csh, sh, or Perl, such as the
714            following:
715
716                    eval '(exit $?0)' && eval 'exec perl -wS $0 ${1+"$@"}'
717                    & eval 'exec /usr/bin/perl -wS $0 $argv:q'
718                            if $running_under_some_shell;
719
720            If the filename supplied contains directory separators (i.e., is
721            an absolute or relative pathname), and if that file is not found,
722            platforms that append file extensions will do so and try to look
723            for the file with those extensions added, one by one.
724
725            On DOS-like platforms, if the program does not contain directory
726            separators, it will first be searched for in the current directory
727            before being searched for on the PATH.  On Unix platforms, the
728            program will be searched for strictly on the PATH.
729
730       -R   Disables the Red Hat module compatibility default search path.
731
732            By default, the Red Hat perl distribution will prepend to the
733            default search path (@INC) the -V:archname subdirectory of each
734            member of the -V:inc_version_list under the perl vendor and site
735            installation directories.  i.e. in shell notation:
736             {-V:vendorlib_stem,-V:sitelib_stem}/{-V:inc_ver‐
737            sion_list}/-V:archname where inc_version_list includes every pre‐
738            vious perl version shipped by Red Hat, to provide compatibility
739            for binary modules installed under previous perl versions. This
740            can be quite a long list of directories to search, which can slow
741            down module loading. You can disable searching these previous perl
742            version architecture specific directories by specifying the -R
743            switch - then the default search path will be as for the default
744            upstream perl release.
745
746       -t   Like -T, but taint checks will issue warnings rather than fatal
747            errors.  These warnings can be controlled normally with "no warn‐
748            ings qw(taint)".
749
750            NOTE: this is not a substitute for -T. This is meant only to be
751            used as a temporary development aid while securing legacy code:
752            for real production code and for new secure code written from
753            scratch always use the real -T.
754
755       -T   forces "taint" checks to be turned on so you can test them.  Ordi‐
756            narily these checks are done only when running setuid or setgid.
757            It's a good idea to turn them on explicitly for programs that run
758            on behalf of someone else whom you might not necessarily trust,
759            such as CGI programs or any internet servers you might write in
760            Perl.  See perlsec for details.  For security reasons, this option
761            must be seen by Perl quite early; usually this means it must
762            appear early on the command line or in the #! line for systems
763            which support that construct.
764
765       -u   This obsolete switch causes Perl to dump core after compiling your
766            program.  You can then in theory take this core dump and turn it
767            into an executable file by using the undump program (not sup‐
768            plied).  This speeds startup at the expense of some disk space
769            (which you can minimize by stripping the executable).  (Still, a
770            "hello world" executable comes out to about 200K on my machine.)
771            If you want to execute a portion of your program before dumping,
772            use the dump() operator instead.  Note: availability of undump is
773            platform specific and may not be available for a specific port of
774            Perl.
775
776            This switch has been superseded in favor of the new Perl code gen‐
777            erator backends to the compiler.  See B and B::Bytecode for
778            details.
779
780       -U   allows Perl to do unsafe operations.  Currently the only "unsafe"
781            operations are attempting to unlink directories while running as
782            superuser, and running setuid programs with fatal taint checks
783            turned into warnings.  Note that the -w switch (or the $^W vari‐
784            able) must be used along with this option to actually generate the
785            taint-check warnings.
786
787       -v   prints the version and patchlevel of your perl executable.
788
789       -V   prints summary of the major perl configuration values and the cur‐
790            rent values of @INC.
791
792       -V:configvar
793            Prints to STDOUT the value of the named configuration variable(s),
794            with multiples when your configvar argument looks like a regex
795            (has non-letters).  For example:
796
797                $ perl -V:libc
798                    libc='/lib/libc-2.2.4.so';
799                $ perl -V:lib.
800                    libs='-lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lc';
801                    libc='/lib/libc-2.2.4.so';
802                $ perl -V:lib.*
803                    libpth='/usr/local/lib /lib /usr/lib';
804                    libs='-lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lc';
805                    lib_ext='.a';
806                    libc='/lib/libc-2.2.4.so';
807                    libperl='libperl.a';
808                    ....
809
810            Additionally, extra colons can be used to control formatting.  A
811            trailing colon suppresses the linefeed and terminator ';', allow‐
812            ing you to embed queries into shell commands.  (mnemonic: PATH
813            separator ':'.)
814
815                $ echo "compression-vars: " `perl -V:z.*: ` " are here !"
816                compression-vars:  zcat='' zip='zip'  are here !
817
818            A leading colon removes the 'name=' part of the response, this
819            allows you to map to the name you need.  (mnemonic: empty label)
820
821                $ echo "goodvfork="`./perl -Ilib -V::usevfork`
822                goodvfork=false;
823
824            Leading and trailing colons can be used together if you need posi‐
825            tional parameter values without the names.  Note that in the case
826            below, the PERL_API params are returned in alphabetical order.
827
828                $ echo building_on `perl -V::osname: -V::PERL_API_.*:` now
829                building_on 'linux' '5' '1' '9' now
830
831       -w   prints warnings about dubious constructs, such as variable names
832            that are mentioned only once and scalar variables that are used
833            before being set, redefined subroutines, references to undefined
834            filehandles or filehandles opened read-only that you are attempt‐
835            ing to write on, values used as a number that don't look like num‐
836            bers, using an array as though it were a scalar, if your subrou‐
837            tines recurse more than 100 deep, and innumerable other things.
838
839            This switch really just enables the internal $^W variable.  You
840            can disable or promote into fatal errors specific warnings using
841            "__WARN__" hooks, as described in perlvar and "warn" in perlfunc.
842            See also perldiag and perltrap.  A new, fine-grained warning
843            facility is also available if you want to manipulate entire
844            classes of warnings; see warnings or perllexwarn.
845
846       -W   Enables all warnings regardless of "no warnings" or $^W.  See per‐
847            llexwarn.
848
849       -X   Disables all warnings regardless of "use warnings" or $^W.  See
850            perllexwarn.
851
852       -x
853       -x directory
854            tells Perl that the program is embedded in a larger chunk of unre‐
855            lated ASCII text, such as in a mail message.  Leading garbage will
856            be discarded until the first line that starts with #! and contains
857            the string "perl".  Any meaningful switches on that line will be
858            applied.  If a directory name is specified, Perl will switch to
859            that directory before running the program.  The -x switch controls
860            only the disposal of leading garbage.  The program must be termi‐
861            nated with "__END__" if there is trailing garbage to be ignored
862            (the program can process any or all of the trailing garbage via
863            the DATA filehandle if desired).
864

ENVIRONMENT

866       HOME        Used if chdir has no argument.
867
868       LOGDIR      Used if chdir has no argument and HOME is not set.
869
870       PATH        Used in executing subprocesses, and in finding the program
871                   if -S is used.
872
873       PERL5LIB    A list of directories in which to look for Perl library
874                   files before looking in the standard library and the cur‐
875                   rent directory.  Any architecture-specific directories
876                   under the specified locations are automatically included if
877                   they exist.  If PERL5LIB is not defined, PERLLIB is used.
878                   Directories are separated (like in PATH) by a colon on
879                   unixish platforms and by a semicolon on Windows (the proper
880                   path separator being given by the command "perl
881                   -V:path_sep").
882
883                   When running taint checks (either because the program was
884                   running setuid or setgid, or the -T switch was used), nei‐
885                   ther variable is used.  The program should instead say:
886
887                       use lib "/my/directory";
888
889       PERL5OPT    Command-line options (switches).  Switches in this variable
890                   are taken as if they were on every Perl command line.  Only
891                   the -[DIMUdmtw] switches are allowed.  When running taint
892                   checks (because the program was running setuid or setgid,
893                   or the -T switch was used), this variable is ignored.  If
894                   PERL5OPT begins with -T, tainting will be enabled, and any
895                   subsequent options ignored.
896
897       PERLIO      A space (or colon) separated list of PerlIO layers. If perl
898                   is built to use PerlIO system for IO (the default) these
899                   layers effect perl's IO.
900
901                   It is conventional to start layer names with a colon e.g.
902                   ":perlio" to emphasise their similarity to variable
903                   "attributes". But the code that parses layer specification
904                   strings (which is also used to decode the PERLIO environ‐
905                   ment variable) treats the colon as a separator.
906
907                   An unset or empty PERLIO is equivalent to ":stdio".
908
909                   The list becomes the default for all perl's IO. Conse‐
910                   quently only built-in layers can appear in this list, as
911                   external layers (such as :encoding()) need IO in  order to
912                   load them!. See "open pragma" for how to add external
913                   encodings as defaults.
914
915                   The layers that it makes sense to include in the PERLIO
916                   environment variable are briefly summarised below. For more
917                   details see PerlIO.
918
919                   :bytes  A pseudolayer that turns off the ":utf8" flag for
920                           the layer below.  Unlikely to be useful on its own
921                           in the global PERLIO environment variable.  You
922                           perhaps were thinking of ":crlf:bytes" or ":per‐
923                           lio:bytes".
924
925                   :crlf   A layer which does CRLF to "\n" translation distin‐
926                           guishing "text" and "binary" files in the manner of
927                           MS-DOS and similar operating systems.  (It cur‐
928                           rently does not mimic MS-DOS as far as treating of
929                           Control-Z as being an end-of-file marker.)
930
931                   :mmap   A layer which implements "reading" of files by
932                           using "mmap()" to make (whole) file appear in the
933                           process's address space, and then using that as
934                           PerlIO's "buffer".
935
936                   :perlio This is a re-implementation of "stdio-like" buffer‐
937                           ing written as a PerlIO "layer".  As such it will
938                           call whatever layer is below it for its operations
939                           (typically ":unix").
940
941                   :pop    An experimental pseudolayer that removes the top‐
942                           most layer.  Use with the same care as is reserved
943                           for nitroglycerin.
944
945                   :raw    A pseudolayer that manipulates other layers.
946                           Applying the ":raw" layer is equivalent to calling
947                           "binmode($fh)".  It makes the stream pass each byte
948                           as-is without any translation.  In particular CRLF
949                           translation, and/or :utf8 intuited from locale are
950                           disabled.
951
952                           Unlike in the earlier versions of Perl ":raw" is
953                           not just the inverse of ":crlf" - other layers
954                           which would affect the binary nature of the stream
955                           are also removed or disabled.
956
957                   :stdio  This layer provides PerlIO interface by wrapping
958                           system's ANSI C "stdio" library calls. The layer
959                           provides both buffering and IO.  Note that ":stdio"
960                           layer does not do CRLF translation even if that is
961                           platforms normal behaviour. You will need a ":crlf"
962                           layer above it to do that.
963
964                   :unix   Low level layer which calls "read", "write" and
965                           "lseek" etc.
966
967                   :utf8   A pseudolayer that turns on a flag on the layer
968                           below to tell perl that output should be in utf8
969                           and that input should be regarded as already in
970                           utf8 form.  May be useful in PERLIO environment
971                           variable to make UTF-8 the default. (To turn off
972                           that behaviour use ":bytes" layer.)
973
974                   :win32  On Win32 platforms this experimental layer uses
975                           native "handle" IO rather than unix-like numeric
976                           file descriptor layer. Known to be buggy in this
977                           release.
978
979                   On all platforms the default set of layers should give
980                   acceptable results.
981
982                   For UNIX platforms that will equivalent of "unix perlio" or
983                   "stdio".  Configure is setup to prefer "stdio" implementa‐
984                   tion if system's library provides for fast access to the
985                   buffer, otherwise it uses the "unix perlio" implementation.
986
987                   On Win32 the default in this release is "unix crlf".
988                   Win32's "stdio" has a number of bugs/mis-features for perl
989                   IO which are somewhat C compiler vendor/version dependent.
990                   Using our own "crlf" layer as the buffer avoids those
991                   issues and makes things more uniform.  The "crlf" layer
992                   provides CRLF to/from "\n" conversion as well as buffering.
993
994                   This release uses "unix" as the bottom layer on Win32 and
995                   so still uses C compiler's numeric file descriptor rou‐
996                   tines. There is an experimental native "win32" layer which
997                   is expected to be enhanced and should eventually be the
998                   default under Win32.
999
1000       PERLIO_DEBUG
1001                   If set to the name of a file or device then certain opera‐
1002                   tions of PerlIO sub-system will be logged to that file
1003                   (opened as append). Typical uses are UNIX:
1004
1005                      PERLIO_DEBUG=/dev/tty perl script ...
1006
1007                   and Win32 approximate 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 cur‐
1017                   rent directory.  If PERL5LIB is defined, PERLLIB is not
1018                   used.
1019
1020       PERL5DB     The command used to load the debugger code.  The default
1021                   is:
1022
1023                           BEGIN { require 'perl5db.pl' }
1024
1025       PERL5DB_THREADED
1026                   If set to a true value, indicates to the debugger that the
1027                   code being debugged uses threads.
1028
1029       PERL5SHELL (specific to the Win32 port)
1030                   May be set to an alternative shell that perl must use
1031                   internally for executing "backtick" commands or system().
1032                   Default is "cmd.exe /x/d/c" on WindowsNT and "command.com
1033                   /c" on Windows95.  The value is considered to be space-sep‐
1034                   arated.  Precede any character that needs to be protected
1035                   (like a space or backslash) with a backslash.
1036
1037                   Note that Perl doesn't use COMSPEC for this purpose because
1038                   COMSPEC has a high degree of variability among users, lead‐
1039                   ing to portability concerns.  Besides, perl can use a shell
1040                   that may not be fit for interactive use, and setting COM‐
1041                   SPEC to such a shell may interfere with the proper func‐
1042                   tioning of other programs (which usually look in COMSPEC to
1043                   find a shell fit for interactive use).
1044
1045       PERL_ALLOW_NON_IFS_LSP (specific to the Win32 port)
1046                   Set to 1 to allow the use of non-IFS compatible LSP's.
1047                   Perl normally searches for an IFS-compatible LSP because
1048                   this is required for its emulation of Windows sockets as
1049                   real filehandles.  However, this may cause problems if you
1050                   have a firewall such as McAfee Guardian which requires all
1051                   applications to use its LSP which is not IFS-compatible,
1052                   because clearly Perl will normally avoid using such an LSP.
1053                   Setting this environment variable to 1 means that Perl will
1054                   simply use the first suitable LSP enumerated in the cata‐
1055                   log, which keeps McAfee Guardian happy (and in that partic‐
1056                   ular case Perl still works too because McAfee Guardian's
1057                   LSP actually plays some other games which allow applica‐
1058                   tions requiring IFS compatibility to work).
1059
1060       PERL_DEBUG_MSTATS
1061                   Relevant only if perl is compiled with the malloc included
1062                   with the perl distribution (that is, if "perl -V:d_mymal‐
1063                   loc" is 'define').  If set, this causes memory statistics
1064                   to be dumped after execution.  If set to an integer greater
1065                   than one, also causes memory statistics to be dumped after
1066                   compilation.
1067
1068       PERL_DESTRUCT_LEVEL
1069                   Relevant only if your perl executable was built with -DDE‐
1070                   BUGGING, this controls the behavior of global destruction
1071                   of objects and other references.  See "PERL_DESTRUCT_LEVEL"
1072                   in perlhack for more information.
1073
1074       PERL_DL_NONLAZY
1075                   Set to one to have perl resolve all undefined symbols when
1076                   it loads a dynamic library.  The default behaviour is to
1077                   resolve symbols when they are used.  Setting this variable
1078                   is useful during testing of extensions as it ensures that
1079                   you get an error on misspelled function names even if the
1080                   test suite doesn't call it.
1081
1082       PERL_ENCODING
1083                   If using the "encoding" pragma without an explicit encoding
1084                   name, the PERL_ENCODING environment variable is consulted
1085                   for an encoding name.
1086
1087       PERL_HASH_SEED
1088                   (Since Perl 5.8.1.)  Used to randomise Perl's internal hash
1089                   function.  To emulate the pre-5.8.1 behaviour, set to an
1090                   integer (zero means exactly the same order as 5.8.0).
1091                   "Pre-5.8.1" means, among other things, that hash keys will
1092                   be ordered the same between different runs of Perl.
1093
1094                   The default behaviour is to randomise unless the
1095                   PERL_HASH_SEED is set.  If Perl has been compiled with
1096                   "-DUSE_HASH_SEED_EXPLICIT", the default behaviour is not to
1097                   randomise unless the PERL_HASH_SEED is set.
1098
1099                   If PERL_HASH_SEED is unset or set to a non-numeric string,
1100                   Perl uses the pseudorandom seed supplied by the operating
1101                   system and libraries.  This means that each different run
1102                   of Perl will have a different ordering of the results of
1103                   keys(), values(), and each().
1104
1105                   Please note that the hash seed is sensitive information.
1106                   Hashes are randomized to protect against local and remote
1107                   attacks against Perl code. By manually setting a seed this
1108                   protection may be partially or completely lost.
1109
1110                   See "Algorithmic Complexity Attacks" in perlsec and
1111                   "PERL_HASH_SEED_DEBUG" for more information.
1112
1113       PERL_HASH_SEED_DEBUG
1114                   (Since Perl 5.8.1.)  Set to one to display (to STDERR) the
1115                   value of the hash seed at the beginning of execution.
1116                   This, combined with "PERL_HASH_SEED" is intended to aid in
1117                   debugging nondeterministic behavior caused by hash random‐
1118                   ization.
1119
1120                   Note that the hash seed is sensitive information: by know‐
1121                   ing it one can craft a denial-of-service attack against
1122                   Perl code, even remotely, see "Algorithmic Complexity
1123                   Attacks" in perlsec for more information.  Do not disclose
1124                   the hash seed to people who don't need to know it.  See
1125                   also hash_seed() of Hash::Util.
1126
1127       PERL_ROOT (specific to the VMS port)
1128                   A translation concealed rooted logical name that contains
1129                   perl and the logical device for the @INC path on VMS only.
1130                   Other logical names that affect perl on VMS include PERL‐
1131                   SHR, PERL_ENV_TABLES, and SYS$TIMEZONE_DIFFERENTIAL but are
1132                   optional and discussed further in perlvms and in README.vms
1133                   in the Perl source distribution.
1134
1135       PERL_SIGNALS
1136                   In Perls 5.8.1 and later.  If set to "unsafe" the
1137                   pre-Perl-5.8.0 signals behaviour (immediate but unsafe) is
1138                   restored.  If set to "safe" the safe (or deferred) signals
1139                   are used.  See "Deferred Signals (Safe Signals)" in per‐
1140                   lipc.
1141
1142       PERL_UNICODE
1143                   Equivalent to the -C command-line switch.  Note that this
1144                   is not a boolean variable-- setting this to "1" is not the
1145                   right way to "enable Unicode" (whatever that would mean).
1146                   You can use "0" to "disable Unicode", though (or alterna‐
1147                   tively unset PERL_UNICODE in your shell before starting
1148                   Perl).  See the description of the "-C" switch for more
1149                   information.
1150
1151       SYS$LOGIN (specific to the VMS port)
1152                   Used if chdir has no argument and HOME and LOGDIR are not
1153                   set.
1154
1155       Perl also has environment variables that control how Perl handles data
1156       specific to particular natural languages.  See perllocale.
1157
1158       Apart from these, Perl uses no other environment variables, except to
1159       make them available to the program being executed, and to child pro‐
1160       cesses.  However, programs running setuid would do well to execute the
1161       following lines before doing anything else, just to keep people honest:
1162
1163           $ENV{PATH}  = '/bin:/usr/bin';    # or whatever you need
1164           $ENV{SHELL} = '/bin/sh' if exists $ENV{SHELL};
1165           delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
1166
1167
1168
1169perl v5.8.8                       2006-01-07                        PERLRUN(1)
Impressum