1PERLVAR(1) Perl Programmers Reference Guide PERLVAR(1)
2
3
4
6 perlvar - Perl predefined variables
7
9 The Syntax of Variable Names
10 Variable names in Perl can have several formats. Usually, they must
11 begin with a letter or underscore, in which case they can be
12 arbitrarily long (up to an internal limit of 251 characters) and may
13 contain letters, digits, underscores, or the special sequence "::" or
14 "'". In this case, the part before the last "::" or "'" is taken to be
15 a package qualifier; see perlmod.
16
17 Perl variable names may also be a sequence of digits or a single
18 punctuation or control character. These names are all reserved for
19 special uses by Perl; for example, the all-digits names are used to
20 hold data captured by backreferences after a regular expression match.
21 Perl has a special syntax for the single-control-character names: It
22 understands "^X" (caret "X") to mean the control-"X" character. For
23 example, the notation $^W (dollar-sign caret "W") is the scalar
24 variable whose name is the single character control-"W". This is
25 better than typing a literal control-"W" into your program.
26
27 Since Perl 5.6, Perl variable names may be alphanumeric strings that
28 begin with control characters (or better yet, a caret). These
29 variables must be written in the form "${^Foo}"; the braces are not
30 optional. "${^Foo}" denotes the scalar variable whose name is a
31 control-"F" followed by two "o"'s. These variables are reserved for
32 future special uses by Perl, except for the ones that begin with "^_"
33 (control-underscore or caret-underscore). No control-character name
34 that begins with "^_" will acquire a special meaning in any future
35 version of Perl; such names may therefore be used safely in programs.
36 $^_ itself, however, is reserved.
37
38 Perl identifiers that begin with digits, control characters, or
39 punctuation characters are exempt from the effects of the "package"
40 declaration and are always forced to be in package "main"; they are
41 also exempt from "strict 'vars'" errors. A few other names are also
42 exempt in these ways:
43
44 ENV STDIN
45 INC STDOUT
46 ARGV STDERR
47 ARGVOUT
48 SIG
49
50 In particular, the special "${^_XYZ}" variables are always taken to be
51 in package "main", regardless of any "package" declarations presently
52 in scope.
53
55 The following names have special meaning to Perl. Most punctuation
56 names have reasonable mnemonics, or analogs in the shells.
57 Nevertheless, if you wish to use long variable names, you need only
58 say:
59
60 use English;
61
62 at the top of your program. This aliases all the short names to the
63 long names in the current package. Some even have medium names,
64 generally borrowed from awk. To avoid a performance hit, if you don't
65 need the $PREMATCH, $MATCH, or $POSTMATCH it's best to use the
66 "English" module without them:
67
68 use English '-no_match_vars';
69
70 Before you continue, note the sort order for variables. In general, we
71 first list the variables in case-insensitive, almost-lexigraphical
72 order (ignoring the "{" or "^" preceding words, as in "${^UNICODE}" or
73 $^T), although $_ and @_ move up to the top of the pile. For variables
74 with the same identifier, we list it in order of scalar, array, hash,
75 and bareword.
76
77 General Variables
78 $ARG
79 $_ The default input and pattern-searching space. The following
80 pairs are equivalent:
81
82 while (<>) {...} # equivalent only in while!
83 while (defined($_ = <>)) {...}
84
85 /^Subject:/
86 $_ =~ /^Subject:/
87
88 tr/a-z/A-Z/
89 $_ =~ tr/a-z/A-Z/
90
91 chomp
92 chomp($_)
93
94 Here are the places where Perl will assume $_ even if you don't
95 use it:
96
97 · The following functions use $_ as a default argument:
98
99 abs, alarm, chomp, chop, chr, chroot, cos, defined, eval,
100 evalbytes, exp, glob, hex, int, lc, lcfirst, length, log,
101 lstat, mkdir, oct, ord, pos, print, quotemeta, readlink,
102 readpipe, ref, require, reverse (in scalar context only),
103 rmdir, sin, split (on its second argument), sqrt, stat,
104 study, uc, ucfirst, unlink, unpack.
105
106 · All file tests ("-f", "-d") except for "-t", which defaults
107 to STDIN. See "-X" in perlfunc
108
109 · The pattern matching operations "m//", "s///" and "tr///"
110 (aka "y///") when used without an "=~" operator.
111
112 · The default iterator variable in a "foreach" loop if no
113 other variable is supplied.
114
115 · The implicit iterator variable in the "grep()" and "map()"
116 functions.
117
118 · The implicit variable of "given()".
119
120 · The default place to put an input record when a "<FH>"
121 operation's result is tested by itself as the sole criterion
122 of a "while" test. Outside a "while" test, this will not
123 happen.
124
125 As $_ is a global variable, this may lead in some cases to
126 unwanted side-effects. As of perl 5.10, you can now use a
127 lexical version of $_ by declaring it in a file or in a block
128 with "my". Moreover, declaring "our $_" restores the global $_
129 in the current scope.
130
131 Mnemonic: underline is understood in certain operations.
132
133 @ARG
134 @_ Within a subroutine the array @_ contains the parameters passed
135 to that subroutine. Inside a subroutine, @_ is the default
136 array for the array operators "push", "pop", "shift", and
137 "unshift".
138
139 See perlsub.
140
141 $LIST_SEPARATOR
142 $" When an array or an array slice is interpolated into a double-
143 quoted string or a similar context such as "/.../", its
144 elements are separated by this value. Default is a space. For
145 example, this:
146
147 print "The array is: @array\n";
148
149 is equivalent to this:
150
151 print "The array is: " . join($", @array) . "\n";
152
153 Mnemonic: works in double-quoted context.
154
155 $PROCESS_ID
156 $PID
157 $$ The process number of the Perl running this script. Though you
158 can set this variable, doing so is generally discouraged,
159 although it can be invaluable for some testing purposes. It
160 will be reset automatically across "fork()" calls.
161
162 Note for Linux and Debian GNU/kFreeBSD users: Before Perl
163 v5.16.0 perl would emulate POSIX semantics on Linux systems
164 using LinuxThreads, a partial implementation of POSIX Threads
165 that has since been superseded by the Native POSIX Thread
166 Library (NPTL).
167
168 LinuxThreads is now obsolete on Linux, and and caching
169 "getpid()" like this made embedding perl unnecessarily complex
170 (since you'd have to manually update the value of $$), so now
171 $$ and "getppid()" will always return the same values as the
172 underlying C library.
173
174 Debian GNU/kFreeBSD systems also used LinuxThreads up until and
175 including the 6.0 release, but after that moved to FreeBSD
176 thread semantics, which are POSIX-like.
177
178 To see if your system is affected by this discrepancy check if
179 "getconf GNU_LIBPTHREAD_VERSION | grep -q NPTL" returns a false
180 value. NTPL threads preserve the POSIX semantics.
181
182 Mnemonic: same as shells.
183
184 $PROGRAM_NAME
185 $0 Contains the name of the program being executed.
186
187 On some (but not all) operating systems assigning to $0
188 modifies the argument area that the "ps" program sees. On some
189 platforms you may have to use special "ps" options or a
190 different "ps" to see the changes. Modifying the $0 is more
191 useful as a way of indicating the current program state than it
192 is for hiding the program you're running.
193
194 Note that there are platform-specific limitations on the
195 maximum length of $0. In the most extreme case it may be
196 limited to the space occupied by the original $0.
197
198 In some platforms there may be arbitrary amount of padding, for
199 example space characters, after the modified name as shown by
200 "ps". In some platforms this padding may extend all the way to
201 the original length of the argument area, no matter what you do
202 (this is the case for example with Linux 2.2).
203
204 Note for BSD users: setting $0 does not completely remove
205 "perl" from the ps(1) output. For example, setting $0 to
206 "foobar" may result in "perl: foobar (perl)" (whether both the
207 "perl: " prefix and the " (perl)" suffix are shown depends on
208 your exact BSD variant and version). This is an operating
209 system feature, Perl cannot help it.
210
211 In multithreaded scripts Perl coordinates the threads so that
212 any thread may modify its copy of the $0 and the change becomes
213 visible to ps(1) (assuming the operating system plays along).
214 Note that the view of $0 the other threads have will not change
215 since they have their own copies of it.
216
217 If the program has been given to perl via the switches "-e" or
218 "-E", $0 will contain the string "-e".
219
220 On Linux as of perl 5.14 the legacy process name will be set
221 with prctl(2), in addition to altering the POSIX name via
222 "argv[0]" as perl has done since version 4.000. Now system
223 utilities that read the legacy process name such as ps, top and
224 killall will recognize the name you set when assigning to $0.
225 The string you supply will be cut off at 16 bytes, this is a
226 limitation imposed by Linux.
227
228 Mnemonic: same as sh and ksh.
229
230 $REAL_GROUP_ID
231 $GID
232 $( The real gid of this process. If you are on a machine that
233 supports membership in multiple groups simultaneously, gives a
234 space separated list of groups you are in. The first number is
235 the one returned by "getgid()", and the subsequent ones by
236 "getgroups()", one of which may be the same as the first
237 number.
238
239 However, a value assigned to $( must be a single number used to
240 set the real gid. So the value given by $( should not be
241 assigned back to $( without being forced numeric, such as by
242 adding zero. Note that this is different to the effective gid
243 ($)) which does take a list.
244
245 You can change both the real gid and the effective gid at the
246 same time by using "POSIX::setgid()". Changes to $( require a
247 check to $! to detect any possible errors after an attempted
248 change.
249
250 Mnemonic: parentheses are used to group things. The real gid
251 is the group you left, if you're running setgid.
252
253 $EFFECTIVE_GROUP_ID
254 $EGID
255 $) The effective gid of this process. If you are on a machine
256 that supports membership in multiple groups simultaneously,
257 gives a space separated list of groups you are in. The first
258 number is the one returned by "getegid()", and the subsequent
259 ones by "getgroups()", one of which may be the same as the
260 first number.
261
262 Similarly, a value assigned to $) must also be a space-
263 separated list of numbers. The first number sets the effective
264 gid, and the rest (if any) are passed to "setgroups()". To get
265 the effect of an empty list for "setgroups()", just repeat the
266 new effective gid; that is, to force an effective gid of 5 and
267 an effectively empty "setgroups()" list, say " $) = "5 5" ".
268
269 You can change both the effective gid and the real gid at the
270 same time by using "POSIX::setgid()" (use only a single numeric
271 argument). Changes to $) require a check to $! to detect any
272 possible errors after an attempted change.
273
274 $<, $>, $( and $) can be set only on machines that support the
275 corresponding set[re][ug]id() routine. $( and $) can be
276 swapped only on machines supporting "setregid()".
277
278 Mnemonic: parentheses are used to group things. The effective
279 gid is the group that's right for you, if you're running
280 setgid.
281
282 $REAL_USER_ID
283 $UID
284 $< The real uid of this process. You can change both the real uid
285 and the effective uid at the same time by using
286 "POSIX::setuid()". Since changes to $< require a system call,
287 check $! after a change attempt to detect any possible errors.
288
289 Mnemonic: it's the uid you came from, if you're running setuid.
290
291 $EFFECTIVE_USER_ID
292 $EUID
293 $> The effective uid of this process. For example:
294
295 $< = $>; # set real to effective uid
296 ($<,$>) = ($>,$<); # swap real and effective uids
297
298 You can change both the effective uid and the real uid at the
299 same time by using "POSIX::setuid()". Changes to $> require a
300 check to $! to detect any possible errors after an attempted
301 change.
302
303 $< and $> can be swapped only on machines supporting
304 "setreuid()".
305
306 Mnemonic: it's the uid you went to, if you're running setuid.
307
308 $SUBSCRIPT_SEPARATOR
309 $SUBSEP
310 $; The subscript separator for multidimensional array emulation.
311 If you refer to a hash element as
312
313 $foo{$a,$b,$c}
314
315 it really means
316
317 $foo{join($;, $a, $b, $c)}
318
319 But don't put
320
321 @foo{$a,$b,$c} # a slice--note the @
322
323 which means
324
325 ($foo{$a},$foo{$b},$foo{$c})
326
327 Default is "\034", the same as SUBSEP in awk. If your keys
328 contain binary data there might not be any safe value for $;.
329
330 Consider using "real" multidimensional arrays as described in
331 perllol.
332
333 Mnemonic: comma (the syntactic subscript separator) is a semi-
334 semicolon.
335
336 $a
337 $b Special package variables when using "sort()", see "sort" in
338 perlfunc. Because of this specialness $a and $b don't need to
339 be declared (using "use vars", or "our()") even when using the
340 "strict 'vars'" pragma. Don't lexicalize them with "my $a" or
341 "my $b" if you want to be able to use them in the "sort()"
342 comparison block or function.
343
344 %ENV The hash %ENV contains your current environment. Setting a
345 value in "ENV" changes the environment for any child processes
346 you subsequently "fork()" off.
347
348 $SYSTEM_FD_MAX
349 $^F The maximum system file descriptor, ordinarily 2. System file
350 descriptors are passed to "exec()"ed processes, while higher
351 file descriptors are not. Also, during an "open()", system
352 file descriptors are preserved even if the "open()" fails
353 (ordinary file descriptors are closed before the "open()" is
354 attempted). The close-on-exec status of a file descriptor will
355 be decided according to the value of $^F when the corresponding
356 file, pipe, or socket was opened, not the time of the "exec()".
357
358 @F The array @F contains the fields of each line read in when
359 autosplit mode is turned on. See perlrun for the -a switch.
360 This array is package-specific, and must be declared or given a
361 full package name if not in package main when running under
362 "strict 'vars'".
363
364 @INC The array @INC contains the list of places that the "do EXPR",
365 "require", or "use" constructs look for their library files.
366 It initially consists of the arguments to any -I command-line
367 switches, followed by the default Perl library, probably
368 /usr/local/lib/perl, followed by ".", to represent the current
369 directory. ("." will not be appended if taint checks are
370 enabled, either by "-T" or by "-t".) If you need to modify
371 this at runtime, you should use the "use lib" pragma to get the
372 machine-dependent library properly loaded also:
373
374 use lib '/mypath/libdir/';
375 use SomeMod;
376
377 You can also insert hooks into the file inclusion system by
378 putting Perl code directly into @INC. Those hooks may be
379 subroutine references, array references or blessed objects.
380 See "require" in perlfunc for details.
381
382 %INC The hash %INC contains entries for each filename included via
383 the "do", "require", or "use" operators. The key is the
384 filename you specified (with module names converted to
385 pathnames), and the value is the location of the file found.
386 The "require" operator uses this hash to determine whether a
387 particular file has already been included.
388
389 If the file was loaded via a hook (e.g. a subroutine reference,
390 see "require" in perlfunc for a description of these hooks),
391 this hook is by default inserted into %INC in place of a
392 filename. Note, however, that the hook may have set the %INC
393 entry by itself to provide some more specific info.
394
395 $INPLACE_EDIT
396 $^I The current value of the inplace-edit extension. Use "undef"
397 to disable inplace editing.
398
399 Mnemonic: value of -i switch.
400
401 $^M By default, running out of memory is an untrappable, fatal
402 error. However, if suitably built, Perl can use the contents
403 of $^M as an emergency memory pool after "die()"ing. Suppose
404 that your Perl were compiled with "-DPERL_EMERGENCY_SBRK" and
405 used Perl's malloc. Then
406
407 $^M = 'a' x (1 << 16);
408
409 would allocate a 64K buffer for use in an emergency. See the
410 INSTALL file in the Perl distribution for information on how to
411 add custom C compilation flags when compiling perl. To
412 discourage casual use of this advanced feature, there is no
413 English long name for this variable.
414
415 This variable was added in Perl 5.004.
416
417 $OSNAME
418 $^O The name of the operating system under which this copy of Perl
419 was built, as determined during the configuration process. For
420 examples see "PLATFORMS" in perlport.
421
422 The value is identical to $Config{'osname'}. See also Config
423 and the -V command-line switch documented in perlrun.
424
425 In Windows platforms, $^O is not very helpful: since it is
426 always "MSWin32", it doesn't tell the difference between
427 95/98/ME/NT/2000/XP/CE/.NET. Use "Win32::GetOSName()" or
428 Win32::GetOSVersion() (see Win32 and perlport) to distinguish
429 between the variants.
430
431 This variable was added in Perl 5.003.
432
433 %SIG The hash %SIG contains signal handlers for signals. For
434 example:
435
436 sub handler { # 1st argument is signal name
437 my($sig) = @_;
438 print "Caught a SIG$sig--shutting down\n";
439 close(LOG);
440 exit(0);
441 }
442
443 $SIG{'INT'} = \&handler;
444 $SIG{'QUIT'} = \&handler;
445 ...
446 $SIG{'INT'} = 'DEFAULT'; # restore default action
447 $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
448
449 Using a value of 'IGNORE' usually has the effect of ignoring
450 the signal, except for the "CHLD" signal. See perlipc for more
451 about this special case.
452
453 Here are some other examples:
454
455 $SIG{"PIPE"} = "Plumber"; # assumes main::Plumber (not
456 # recommended)
457 $SIG{"PIPE"} = \&Plumber; # just fine; assume current
458 # Plumber
459 $SIG{"PIPE"} = *Plumber; # somewhat esoteric
460 $SIG{"PIPE"} = Plumber(); # oops, what did Plumber()
461 # return??
462
463 Be sure not to use a bareword as the name of a signal handler,
464 lest you inadvertently call it.
465
466 If your system has the "sigaction()" function then signal
467 handlers are installed using it. This means you get reliable
468 signal handling.
469
470 The default delivery policy of signals changed in Perl 5.8.0
471 from immediate (also known as "unsafe") to deferred, also known
472 as "safe signals". See perlipc for more information.
473
474 Certain internal hooks can be also set using the %SIG hash.
475 The routine indicated by $SIG{__WARN__} is called when a
476 warning message is about to be printed. The warning message is
477 passed as the first argument. The presence of a "__WARN__"
478 hook causes the ordinary printing of warnings to "STDERR" to be
479 suppressed. You can use this to save warnings in a variable,
480 or turn warnings into fatal errors, like this:
481
482 local $SIG{__WARN__} = sub { die $_[0] };
483 eval $proggie;
484
485 As the 'IGNORE' hook is not supported by "__WARN__", you can
486 disable warnings using the empty subroutine:
487
488 local $SIG{__WARN__} = sub {};
489
490 The routine indicated by $SIG{__DIE__} is called when a fatal
491 exception is about to be thrown. The error message is passed
492 as the first argument. When a "__DIE__" hook routine returns,
493 the exception processing continues as it would have in the
494 absence of the hook, unless the hook routine itself exits via a
495 "goto &sub", a loop exit, or a "die()". The "__DIE__" handler
496 is explicitly disabled during the call, so that you can die
497 from a "__DIE__" handler. Similarly for "__WARN__".
498
499 Due to an implementation glitch, the $SIG{__DIE__} hook is
500 called even inside an "eval()". Do not use this to rewrite a
501 pending exception in $@, or as a bizarre substitute for
502 overriding "CORE::GLOBAL::die()". This strange action at a
503 distance may be fixed in a future release so that $SIG{__DIE__}
504 is only called if your program is about to exit, as was the
505 original intent. Any other use is deprecated.
506
507 "__DIE__"/"__WARN__" handlers are very special in one respect:
508 they may be called to report (probable) errors found by the
509 parser. In such a case the parser may be in inconsistent
510 state, so any attempt to evaluate Perl code from such a handler
511 will probably result in a segfault. This means that warnings
512 or errors that result from parsing Perl should be used with
513 extreme caution, like this:
514
515 require Carp if defined $^S;
516 Carp::confess("Something wrong") if defined &Carp::confess;
517 die "Something wrong, but could not load Carp to give "
518 . "backtrace...\n\t"
519 . "To see backtrace try starting Perl with -MCarp switch";
520
521 Here the first line will load "Carp" unless it is the parser
522 who called the handler. The second line will print backtrace
523 and die if "Carp" was available. The third line will be
524 executed only if "Carp" was not available.
525
526 Having to even think about the $^S variable in your exception
527 handlers is simply wrong. $SIG{__DIE__} as currently
528 implemented invites grievous and difficult to track down
529 errors. Avoid it and use an "END{}" or CORE::GLOBAL::die
530 override instead.
531
532 See "die" in perlfunc, "warn" in perlfunc, "eval" in perlfunc,
533 and warnings for additional information.
534
535 $BASETIME
536 $^T The time at which the program began running, in seconds since
537 the epoch (beginning of 1970). The values returned by the -M,
538 -A, and -C filetests are based on this value.
539
540 $PERL_VERSION
541 $^V The revision, version, and subversion of the Perl interpreter,
542 represented as a "version" object.
543
544 This variable first appeared in perl 5.6.0; earlier versions of
545 perl will see an undefined value. Before perl 5.10.0 $^V was
546 represented as a v-string.
547
548 $^V can be used to determine whether the Perl interpreter
549 executing a script is in the right range of versions. For
550 example:
551
552 warn "Hashes not randomized!\n" if !$^V or $^V lt v5.8.1
553
554 To convert $^V into its string representation use "sprintf()"'s
555 "%vd" conversion:
556
557 printf "version is v%vd\n", $^V; # Perl's version
558
559 See the documentation of "use VERSION" and "require VERSION"
560 for a convenient way to fail if the running Perl interpreter is
561 too old.
562
563 See also $] for an older representation of the Perl version.
564
565 This variable was added in Perl 5.6.
566
567 Mnemonic: use ^V for Version Control.
568
569 ${^WIN32_SLOPPY_STAT}
570 If this variable is set to a true value, then "stat()" on
571 Windows will not try to open the file. This means that the
572 link count cannot be determined and file attributes may be out
573 of date if additional hardlinks to the file exist. On the
574 other hand, not opening the file is considerably faster,
575 especially for files on network drives.
576
577 This variable could be set in the sitecustomize.pl file to
578 configure the local Perl installation to use "sloppy" "stat()"
579 by default. See the documentation for -f in perlrun for more
580 information about site customization.
581
582 This variable was added in Perl 5.10.
583
584 $EXECUTABLE_NAME
585 $^X The name used to execute the current copy of Perl, from C's
586 "argv[0]" or (where supported) /proc/self/exe.
587
588 Depending on the host operating system, the value of $^X may be
589 a relative or absolute pathname of the perl program file, or
590 may be the string used to invoke perl but not the pathname of
591 the perl program file. Also, most operating systems permit
592 invoking programs that are not in the PATH environment
593 variable, so there is no guarantee that the value of $^X is in
594 PATH. For VMS, the value may or may not include a version
595 number.
596
597 You usually can use the value of $^X to re-invoke an
598 independent copy of the same perl that is currently running,
599 e.g.,
600
601 @first_run = `$^X -le "print int rand 100 for 1..100"`;
602
603 But recall that not all operating systems support forking or
604 capturing of the output of commands, so this complex statement
605 may not be portable.
606
607 It is not safe to use the value of $^X as a path name of a
608 file, as some operating systems that have a mandatory suffix on
609 executable files do not require use of the suffix when invoking
610 a command. To convert the value of $^X to a path name, use the
611 following statements:
612
613 # Build up a set of file names (not command names).
614 use Config;
615 my $this_perl = $^X;
616 if ($^O ne 'VMS') {
617 $this_perl .= $Config{_exe}
618 unless $this_perl =~ m/$Config{_exe}$/i;
619 }
620
621 Because many operating systems permit anyone with read access
622 to the Perl program file to make a copy of it, patch the copy,
623 and then execute the copy, the security-conscious Perl
624 programmer should take care to invoke the installed copy of
625 perl, not the copy referenced by $^X. The following statements
626 accomplish this goal, and produce a pathname that can be
627 invoked as a command or referenced as a file.
628
629 use Config;
630 my $secure_perl_path = $Config{perlpath};
631 if ($^O ne 'VMS') {
632 $secure_perl_path .= $Config{_exe}
633 unless $secure_perl_path =~ m/$Config{_exe}$/i;
634 }
635
636 Variables related to regular expressions
637 Most of the special variables related to regular expressions are side
638 effects. Perl sets these variables when it has a successful match, so
639 you should check the match result before using them. For instance:
640
641 if( /P(A)TT(ER)N/ ) {
642 print "I found $1 and $2\n";
643 }
644
645 These variables are read-only and dynamically-scoped, unless we note
646 otherwise.
647
648 The dynamic nature of the regular expression variables means that their
649 value is limited to the block that they are in, as demonstrated by this
650 bit of code:
651
652 my $outer = 'Wallace and Grommit';
653 my $inner = 'Mutt and Jeff';
654
655 my $pattern = qr/(\S+) and (\S+)/;
656
657 sub show_n { print "\$1 is $1; \$2 is $2\n" }
658
659 {
660 OUTER:
661 show_n() if $outer =~ m/$pattern/;
662
663 INNER: {
664 show_n() if $inner =~ m/$pattern/;
665 }
666
667 show_n();
668 }
669
670 The output shows that while in the "OUTER" block, the values of $1 and
671 $2 are from the match against $outer. Inside the "INNER" block, the
672 values of $1 and $2 are from the match against $inner, but only until
673 the end of the block (i.e. the dynamic scope). After the "INNER" block
674 completes, the values of $1 and $2 return to the values for the match
675 against $outer even though we have not made another match:
676
677 $1 is Wallace; $2 is Grommit
678 $1 is Mutt; $2 is Jeff
679 $1 is Wallace; $2 is Grommit
680
681 Due to an unfortunate accident of Perl's implementation, "use English"
682 imposes a considerable performance penalty on all regular expression
683 matches in a program because it uses the "$`", $&, and "$'", regardless
684 of whether they occur in the scope of "use English". For that reason,
685 saying "use English" in libraries is strongly discouraged unless you
686 import it without the match variables:
687
688 use English '-no_match_vars'
689
690 The "Devel::NYTProf" and "Devel::FindAmpersand" modules can help you
691 find uses of these problematic match variables in your code.
692
693 Since Perl 5.10, you can use the "/p" match operator flag and the
694 "${^PREMATCH}", "${^MATCH}", and "${^POSTMATCH}" variables instead so
695 you only suffer the performance penalties.
696
697 $<digits> ($1, $2, ...)
698 Contains the subpattern from the corresponding set of capturing
699 parentheses from the last successful pattern match, not
700 counting patterns matched in nested blocks that have been
701 exited already.
702
703 These variables are read-only and dynamically-scoped.
704
705 Mnemonic: like \digits.
706
707 $MATCH
708 $& The string matched by the last successful pattern match (not
709 counting any matches hidden within a BLOCK or "eval()" enclosed
710 by the current BLOCK).
711
712 The use of this variable anywhere in a program imposes a
713 considerable performance penalty on all regular expression
714 matches. To avoid this penalty, you can extract the same
715 substring by using "@-". Starting with Perl 5.10, you can use
716 the "/p" match flag and the "${^MATCH}" variable to do the same
717 thing for particular match operations.
718
719 This variable is read-only and dynamically-scoped.
720
721 Mnemonic: like "&" in some editors.
722
723 ${^MATCH}
724 This is similar to $& ($MATCH) except that it does not incur
725 the performance penalty associated with that variable, and is
726 only guaranteed to return a defined value when the pattern was
727 compiled or executed with the "/p" modifier.
728
729 This variable was added in Perl 5.10.
730
731 This variable is read-only and dynamically-scoped.
732
733 $PREMATCH
734 $` The string preceding whatever was matched by the last
735 successful pattern match, not counting any matches hidden
736 within a BLOCK or "eval" enclosed by the current BLOCK.
737
738 The use of this variable anywhere in a program imposes a
739 considerable performance penalty on all regular expression
740 matches. To avoid this penalty, you can extract the same
741 substring by using "@-". Starting with Perl 5.10, you can use
742 the "/p" match flag and the "${^PREMATCH}" variable to do the
743 same thing for particular match operations.
744
745 This variable is read-only and dynamically-scoped.
746
747 Mnemonic: "`" often precedes a quoted string.
748
749 ${^PREMATCH}
750 This is similar to "$`" ($PREMATCH) except that it does not
751 incur the performance penalty associated with that variable,
752 and is only guaranteed to return a defined value when the
753 pattern was compiled or executed with the "/p" modifier.
754
755 This variable was added in Perl 5.10
756
757 This variable is read-only and dynamically-scoped.
758
759 $POSTMATCH
760 $' The string following whatever was matched by the last
761 successful pattern match (not counting any matches hidden
762 within a BLOCK or "eval()" enclosed by the current BLOCK).
763 Example:
764
765 local $_ = 'abcdefghi';
766 /def/;
767 print "$`:$&:$'\n"; # prints abc:def:ghi
768
769 The use of this variable anywhere in a program imposes a
770 considerable performance penalty on all regular expression
771 matches. To avoid this penalty, you can extract the same
772 substring by using "@-". Starting with Perl 5.10, you can use
773 the "/p" match flag and the "${^POSTMATCH}" variable to do the
774 same thing for particular match operations.
775
776 This variable is read-only and dynamically-scoped.
777
778 Mnemonic: "'" often follows a quoted string.
779
780 ${^POSTMATCH}
781 This is similar to "$'" ($POSTMATCH) except that it does not
782 incur the performance penalty associated with that variable,
783 and is only guaranteed to return a defined value when the
784 pattern was compiled or executed with the "/p" modifier.
785
786 This variable was added in Perl 5.10.
787
788 This variable is read-only and dynamically-scoped.
789
790 $LAST_PAREN_MATCH
791 $+ The text matched by the last bracket of the last successful
792 search pattern. This is useful if you don't know which one of
793 a set of alternative patterns matched. For example:
794
795 /Version: (.*)|Revision: (.*)/ && ($rev = $+);
796
797 This variable is read-only and dynamically-scoped.
798
799 Mnemonic: be positive and forward looking.
800
801 $LAST_SUBMATCH_RESULT
802 $^N The text matched by the used group most-recently closed (i.e.
803 the group with the rightmost closing parenthesis) of the last
804 successful search pattern.
805
806 This is primarily used inside "(?{...})" blocks for examining
807 text recently matched. For example, to effectively capture
808 text to a variable (in addition to $1, $2, etc.), replace
809 "(...)" with
810
811 (?:(...)(?{ $var = $^N }))
812
813 By setting and then using $var in this way relieves you from
814 having to worry about exactly which numbered set of parentheses
815 they are.
816
817 This variable was added in Perl 5.8.
818
819 Mnemonic: the (possibly) Nested parenthesis that most recently
820 closed.
821
822 @LAST_MATCH_END
823 @+ This array holds the offsets of the ends of the last successful
824 submatches in the currently active dynamic scope. $+[0] is the
825 offset into the string of the end of the entire match. This is
826 the same value as what the "pos" function returns when called
827 on the variable that was matched against. The nth element of
828 this array holds the offset of the nth submatch, so $+[1] is
829 the offset past where $1 ends, $+[2] the offset past where $2
830 ends, and so on. You can use $#+ to determine how many
831 subgroups were in the last successful match. See the examples
832 given for the "@-" variable.
833
834 This variable was added in Perl 5.6.
835
836 %LAST_PAREN_MATCH
837 %+ Similar to "@+", the "%+" hash allows access to the named
838 capture buffers, should they exist, in the last successful
839 match in the currently active dynamic scope.
840
841 For example, $+{foo} is equivalent to $1 after the following
842 match:
843
844 'foo' =~ /(?<foo>foo)/;
845
846 The keys of the "%+" hash list only the names of buffers that
847 have captured (and that are thus associated to defined values).
848
849 The underlying behaviour of "%+" is provided by the
850 Tie::Hash::NamedCapture module.
851
852 Note: "%-" and "%+" are tied views into a common internal hash
853 associated with the last successful regular expression.
854 Therefore mixing iterative access to them via "each" may have
855 unpredictable results. Likewise, if the last successful match
856 changes, then the results may be surprising.
857
858 This variable was added in Perl 5.10.
859
860 This variable is read-only and dynamically-scoped.
861
862 @LAST_MATCH_START
863 @- "$-[0]" is the offset of the start of the last successful
864 match. "$-["n"]" is the offset of the start of the substring
865 matched by n-th subpattern, or undef if the subpattern did not
866 match.
867
868 Thus, after a match against $_, $& coincides with "substr $_,
869 $-[0], $+[0] - $-[0]". Similarly, $n coincides with "substr
870 $_, $-[n], $+[n] - $-[n]" if "$-[n]" is defined, and $+
871 coincides with "substr $_, $-[$#-], $+[$#-] - $-[$#-]". One
872 can use "$#-" to find the last matched subgroup in the last
873 successful match. Contrast with $#+, the number of subgroups
874 in the regular expression. Compare with "@+".
875
876 This array holds the offsets of the beginnings of the last
877 successful submatches in the currently active dynamic scope.
878 "$-[0]" is the offset into the string of the beginning of the
879 entire match. The nth element of this array holds the offset
880 of the nth submatch, so "$-[1]" is the offset where $1 begins,
881 "$-[2]" the offset where $2 begins, and so on.
882
883 After a match against some variable $var:
884
885 "$`" is the same as "substr($var, 0, $-[0])"
886 $& is the same as "substr($var, $-[0], $+[0] - $-[0])"
887 "$'" is the same as "substr($var, $+[0])"
888 $1 is the same as "substr($var, $-[1], $+[1] - $-[1])"
889 $2 is the same as "substr($var, $-[2], $+[2] - $-[2])"
890 $3 is the same as "substr($var, $-[3], $+[3] - $-[3])"
891
892 This variable was added in Perl 5.6.
893
894 %LAST_MATCH_START
895 %- Similar to "%+", this variable allows access to the named
896 capture groups in the last successful match in the currently
897 active dynamic scope. To each capture group name found in the
898 regular expression, it associates a reference to an array
899 containing the list of values captured by all buffers with that
900 name (should there be several of them), in the order where they
901 appear.
902
903 Here's an example:
904
905 if ('1234' =~ /(?<A>1)(?<B>2)(?<A>3)(?<B>4)/) {
906 foreach my $bufname (sort keys %-) {
907 my $ary = $-{$bufname};
908 foreach my $idx (0..$#$ary) {
909 print "\$-{$bufname}[$idx] : ",
910 (defined($ary->[$idx])
911 ? "'$ary->[$idx]'"
912 : "undef"),
913 "\n";
914 }
915 }
916 }
917
918 would print out:
919
920 $-{A}[0] : '1'
921 $-{A}[1] : '3'
922 $-{B}[0] : '2'
923 $-{B}[1] : '4'
924
925 The keys of the "%-" hash correspond to all buffer names found
926 in the regular expression.
927
928 The behaviour of "%-" is implemented via the
929 Tie::Hash::NamedCapture module.
930
931 Note: "%-" and "%+" are tied views into a common internal hash
932 associated with the last successful regular expression.
933 Therefore mixing iterative access to them via "each" may have
934 unpredictable results. Likewise, if the last successful match
935 changes, then the results may be surprising.
936
937 This variable was added in Perl 5.10
938
939 This variable is read-only and dynamically-scoped.
940
941 $LAST_REGEXP_CODE_RESULT
942 $^R The result of evaluation of the last successful "(?{ code })"
943 regular expression assertion (see perlre). May be written to.
944
945 This variable was added in Perl 5.005.
946
947 ${^RE_DEBUG_FLAGS}
948 The current value of the regex debugging flags. Set to 0 for
949 no debug output even when the "re 'debug'" module is loaded.
950 See re for details.
951
952 This variable was added in Perl 5.10.
953
954 ${^RE_TRIE_MAXBUF}
955 Controls how certain regex optimisations are applied and how
956 much memory they utilize. This value by default is 65536 which
957 corresponds to a 512kB temporary cache. Set this to a higher
958 value to trade memory for speed when matching large
959 alternations. Set it to a lower value if you want the
960 optimisations to be as conservative of memory as possible but
961 still occur, and set it to a negative value to prevent the
962 optimisation and conserve the most memory. Under normal
963 situations this variable should be of no interest to you.
964
965 This variable was added in Perl 5.10.
966
967 Variables related to filehandles
968 Variables that depend on the currently selected filehandle may be set
969 by calling an appropriate object method on the "IO::Handle" object,
970 although this is less efficient than using the regular built-in
971 variables. (Summary lines below for this contain the word HANDLE.)
972 First you must say
973
974 use IO::Handle;
975
976 after which you may use either
977
978 method HANDLE EXPR
979
980 or more safely,
981
982 HANDLE->method(EXPR)
983
984 Each method returns the old value of the "IO::Handle" attribute. The
985 methods each take an optional EXPR, which, if supplied, specifies the
986 new value for the "IO::Handle" attribute in question. If not supplied,
987 most methods do nothing to the current value--except for "autoflush()",
988 which will assume a 1 for you, just to be different.
989
990 Because loading in the "IO::Handle" class is an expensive operation,
991 you should learn how to use the regular built-in variables.
992
993 A few of these variables are considered "read-only". This means that
994 if you try to assign to this variable, either directly or indirectly
995 through a reference, you'll raise a run-time exception.
996
997 You should be very careful when modifying the default values of most
998 special variables described in this document. In most cases you want
999 to localize these variables before changing them, since if you don't,
1000 the change may affect other modules which rely on the default values of
1001 the special variables that you have changed. This is one of the
1002 correct ways to read the whole file at once:
1003
1004 open my $fh, "<", "foo" or die $!;
1005 local $/; # enable localized slurp mode
1006 my $content = <$fh>;
1007 close $fh;
1008
1009 But the following code is quite bad:
1010
1011 open my $fh, "<", "foo" or die $!;
1012 undef $/; # enable slurp mode
1013 my $content = <$fh>;
1014 close $fh;
1015
1016 since some other module, may want to read data from some file in the
1017 default "line mode", so if the code we have just presented has been
1018 executed, the global value of $/ is now changed for any other code
1019 running inside the same Perl interpreter.
1020
1021 Usually when a variable is localized you want to make sure that this
1022 change affects the shortest scope possible. So unless you are already
1023 inside some short "{}" block, you should create one yourself. For
1024 example:
1025
1026 my $content = '';
1027 open my $fh, "<", "foo" or die $!;
1028 {
1029 local $/;
1030 $content = <$fh>;
1031 }
1032 close $fh;
1033
1034 Here is an example of how your own code can go broken:
1035
1036 for ( 1..3 ){
1037 $\ = "\r\n";
1038 nasty_break();
1039 print "$_";
1040 }
1041
1042 sub nasty_break {
1043 $\ = "\f";
1044 # do something with $_
1045 }
1046
1047 You probably expect this code to print the equivalent of
1048
1049 "1\r\n2\r\n3\r\n"
1050
1051 but instead you get:
1052
1053 "1\f2\f3\f"
1054
1055 Why? Because "nasty_break()" modifies "$\" without localizing it first.
1056 The value you set in "nasty_break()" is still there when you return.
1057 The fix is to add "local()" so the value doesn't leak out of
1058 "nasty_break()":
1059
1060 local $\ = "\f";
1061
1062 It's easy to notice the problem in such a short example, but in more
1063 complicated code you are looking for trouble if you don't localize
1064 changes to the special variables.
1065
1066 $ARGV Contains the name of the current file when reading from "<>".
1067
1068 @ARGV The array @ARGV contains the command-line arguments intended
1069 for the script. $#ARGV is generally the number of arguments
1070 minus one, because $ARGV[0] is the first argument, not the
1071 program's command name itself. See "$0" for the command name.
1072
1073 ARGV The special filehandle that iterates over command-line
1074 filenames in @ARGV. Usually written as the null filehandle in
1075 the angle operator "<>". Note that currently "ARGV" only has
1076 its magical effect within the "<>" operator; elsewhere it is
1077 just a plain filehandle corresponding to the last file opened
1078 by "<>". In particular, passing "\*ARGV" as a parameter to a
1079 function that expects a filehandle may not cause your function
1080 to automatically read the contents of all the files in @ARGV.
1081
1082 ARGVOUT The special filehandle that points to the currently open output
1083 file when doing edit-in-place processing with -i. Useful when
1084 you have to do a lot of inserting and don't want to keep
1085 modifying $_. See perlrun for the -i switch.
1086
1087 Handle->output_field_separator( EXPR )
1088 $OUTPUT_FIELD_SEPARATOR
1089 $OFS
1090 $, The output field separator for the print operator. If defined,
1091 this value is printed between each of print's arguments.
1092 Default is "undef".
1093
1094 Mnemonic: what is printed when there is a "," in your print
1095 statement.
1096
1097 HANDLE->input_line_number( EXPR )
1098 $INPUT_LINE_NUMBER
1099 $NR
1100 $. Current line number for the last filehandle accessed.
1101
1102 Each filehandle in Perl counts the number of lines that have
1103 been read from it. (Depending on the value of $/, Perl's idea
1104 of what constitutes a line may not match yours.) When a line
1105 is read from a filehandle (via "readline()" or "<>"), or when
1106 "tell()" or "seek()" is called on it, $. becomes an alias to
1107 the line counter for that filehandle.
1108
1109 You can adjust the counter by assigning to $., but this will
1110 not actually move the seek pointer. Localizing $. will not
1111 localize the filehandle's line count. Instead, it will
1112 localize perl's notion of which filehandle $. is currently
1113 aliased to.
1114
1115 $. is reset when the filehandle is closed, but not when an open
1116 filehandle is reopened without an intervening "close()". For
1117 more details, see "I/O Operators" in perlop. Because "<>"
1118 never does an explicit close, line numbers increase across
1119 "ARGV" files (but see examples in "eof" in perlfunc).
1120
1121 You can also use "HANDLE->input_line_number(EXPR)" to access
1122 the line counter for a given filehandle without having to worry
1123 about which handle you last accessed.
1124
1125 Mnemonic: many programs use "." to mean the current line
1126 number.
1127
1128 HANDLE->input_record_separator( EXPR )
1129 $INPUT_RECORD_SEPARATOR
1130 $RS
1131 $/ The input record separator, newline by default. This
1132 influences Perl's idea of what a "line" is. Works like awk's
1133 RS variable, including treating empty lines as a terminator if
1134 set to the null string (an empty line cannot contain any spaces
1135 or tabs). You may set it to a multi-character string to match
1136 a multi-character terminator, or to "undef" to read through the
1137 end of file. Setting it to "\n\n" means something slightly
1138 different than setting to "", if the file contains consecutive
1139 empty lines. Setting to "" will treat two or more consecutive
1140 empty lines as a single empty line. Setting to "\n\n" will
1141 blindly assume that the next input character belongs to the
1142 next paragraph, even if it's a newline.
1143
1144 local $/; # enable "slurp" mode
1145 local $_ = <FH>; # whole file now here
1146 s/\n[ \t]+/ /g;
1147
1148 Remember: the value of $/ is a string, not a regex. awk has to
1149 be better for something. :-)
1150
1151 Setting $/ to a reference to an integer, scalar containing an
1152 integer, or scalar that's convertible to an integer will
1153 attempt to read records instead of lines, with the maximum
1154 record size being the referenced integer. So this:
1155
1156 local $/ = \32768; # or \"32768", or \$var_containing_32768
1157 open my $fh, "<", $myfile or die $!;
1158 local $_ = <$fh>;
1159
1160 will read a record of no more than 32768 bytes from FILE. If
1161 you're not reading from a record-oriented file (or your OS
1162 doesn't have record-oriented files), then you'll likely get a
1163 full chunk of data with every read. If a record is larger than
1164 the record size you've set, you'll get the record back in
1165 pieces. Trying to set the record size to zero or less will
1166 cause reading in the (rest of the) whole file.
1167
1168 On VMS only, record reads bypass PerlIO layers and any
1169 associated buffering,so you must not mix record and non-record
1170 reads on the same filehandle. Record mode mixes with line mode
1171 only when the same buffering layer is in use for both modes.
1172
1173 If you perform a record read on a FILE with an encoding layer
1174 such as ":encoding(latin1)" or ":utf8", you may get an invalid
1175 string as a result, may leave the FILE positioned between
1176 characters in the stream and may not be reading the number of
1177 bytes from the underlying file that you specified. This
1178 behaviour may change without warning in a future version of
1179 perl.
1180
1181 See also "Newlines" in perlport. Also see "$.".
1182
1183 Mnemonic: / delimits line boundaries when quoting poetry.
1184
1185 Handle->output_record_separator( EXPR )
1186 $OUTPUT_RECORD_SEPARATOR
1187 $ORS
1188 $\ The output record separator for the print operator. If
1189 defined, this value is printed after the last of print's
1190 arguments. Default is "undef".
1191
1192 Mnemonic: you set "$\" instead of adding "\n" at the end of the
1193 print. Also, it's just like $/, but it's what you get "back"
1194 from Perl.
1195
1196 HANDLE->autoflush( EXPR )
1197 $OUTPUT_AUTOFLUSH
1198 $| If set to nonzero, forces a flush right away and after every
1199 write or print on the currently selected output channel.
1200 Default is 0 (regardless of whether the channel is really
1201 buffered by the system or not; $| tells you only whether you've
1202 asked Perl explicitly to flush after each write). STDOUT will
1203 typically be line buffered if output is to the terminal and
1204 block buffered otherwise. Setting this variable is useful
1205 primarily when you are outputting to a pipe or socket, such as
1206 when you are running a Perl program under rsh and want to see
1207 the output as it's happening. This has no effect on input
1208 buffering. See "getc" in perlfunc for that. See "select" in
1209 perlfunc on how to select the output channel. See also
1210 IO::Handle.
1211
1212 Mnemonic: when you want your pipes to be piping hot.
1213
1214 Variables related to formats
1215
1216 The special variables for formats are a subset of those for
1217 filehandles. See perlform for more information about Perl's formats.
1218
1219 $ACCUMULATOR
1220 $^A The current value of the "write()" accumulator for "format()"
1221 lines. A format contains "formline()" calls that put their
1222 result into $^A. After calling its format, "write()" prints
1223 out the contents of $^A and empties. So you never really see
1224 the contents of $^A unless you call "formline()" yourself and
1225 then look at it. See perlform and "formline PICTURE,LIST" in
1226 perlfunc.
1227
1228 HANDLE->format_formfeed(EXPR)
1229 $FORMAT_FORMFEED
1230 $^L What formats output as a form feed. The default is "\f".
1231
1232 HANDLE->format_page_number(EXPR)
1233 $FORMAT_PAGE_NUMBER
1234 $% The current page number of the currently selected output
1235 channel.
1236
1237 Mnemonic: "%" is page number in nroff.
1238
1239 HANDLE->format_lines_left(EXPR)
1240 $FORMAT_LINES_LEFT
1241 $- The number of lines left on the page of the currently selected
1242 output channel.
1243
1244 Mnemonic: lines_on_page - lines_printed.
1245
1246 Handle->format_line_break_characters EXPR
1247 $FORMAT_LINE_BREAK_CHARACTERS
1248 $: The current set of characters after which a string may be
1249 broken to fill continuation fields (starting with "^") in a
1250 format. The default is " \n-", to break on a space, newline,
1251 or a hyphen.
1252
1253 Mnemonic: a "colon" in poetry is a part of a line.
1254
1255 HANDLE->format_lines_per_page(EXPR)
1256 $FORMAT_LINES_PER_PAGE
1257 $= The current page length (printable lines) of the currently
1258 selected output channel. The default is 60.
1259
1260 Mnemonic: = has horizontal lines.
1261
1262 HANDLE->format_top_name(EXPR)
1263 $FORMAT_TOP_NAME
1264 $^ The name of the current top-of-page format for the currently
1265 selected output channel. The default is the name of the
1266 filehandle with "_TOP" appended. For example, the default
1267 format top name for the "STDOUT" filehandle is "STDOUT_TOP".
1268
1269 Mnemonic: points to top of page.
1270
1271 HANDLE->format_name(EXPR)
1272 $FORMAT_NAME
1273 $~ The name of the current report format for the currently
1274 selected output channel. The default format name is the same
1275 as the filehandle name. For example, the default format name
1276 for the "STDOUT" filehandle is just "STDOUT".
1277
1278 Mnemonic: brother to $^.
1279
1280 Error Variables
1281 The variables $@, $!, $^E, and $? contain information about different
1282 types of error conditions that may appear during execution of a Perl
1283 program. The variables are shown ordered by the "distance" between the
1284 subsystem which reported the error and the Perl process. They
1285 correspond to errors detected by the Perl interpreter, C library,
1286 operating system, or an external program, respectively.
1287
1288 To illustrate the differences between these variables, consider the
1289 following Perl expression, which uses a single-quoted string. After
1290 execution of this statement, perl may have set all four special error
1291 variables:
1292
1293 eval q{
1294 open my $pipe, "/cdrom/install |" or die $!;
1295 my @res = <$pipe>;
1296 close $pipe or die "bad pipe: $?, $!";
1297 };
1298
1299 When perl executes the "eval()" expression, it translates the "open()",
1300 "<PIPE>", and "close" calls in the C run-time library and thence to the
1301 operating system kernel. perl sets $! to the C library's "errno" if
1302 one of these calls fails.
1303
1304 $@ is set if the string to be "eval"-ed did not compile (this may
1305 happen if "open" or "close" were imported with bad prototypes), or if
1306 Perl code executed during evaluation "die()"d. In these cases the
1307 value of $@ is the compile error, or the argument to "die" (which will
1308 interpolate $! and $?). (See also Fatal, though.)
1309
1310 Under a few operating systems, $^E may contain a more verbose error
1311 indicator, such as in this case, "CDROM tray not closed." Systems that
1312 do not support extended error messages leave $^E the same as $!.
1313
1314 Finally, $? may be set to non-0 value if the external program
1315 /cdrom/install fails. The upper eight bits reflect specific error
1316 conditions encountered by the program (the program's "exit()" value).
1317 The lower eight bits reflect mode of failure, like signal death and
1318 core dump information. See wait(2) for details. In contrast to $! and
1319 $^E, which are set only if error condition is detected, the variable $?
1320 is set on each "wait" or pipe "close", overwriting the old value. This
1321 is more like $@, which on every "eval()" is always set on failure and
1322 cleared on success.
1323
1324 For more details, see the individual descriptions at $@, $!, $^E, and
1325 $?.
1326
1327 ${^CHILD_ERROR_NATIVE}
1328 The native status returned by the last pipe close, backtick
1329 ("``") command, successful call to "wait()" or "waitpid()", or
1330 from the "system()" operator. On POSIX-like systems this value
1331 can be decoded with the WIFEXITED, WEXITSTATUS, WIFSIGNALED,
1332 WTERMSIG, WIFSTOPPED, WSTOPSIG and WIFCONTINUED functions
1333 provided by the POSIX module.
1334
1335 Under VMS this reflects the actual VMS exit status; i.e. it is
1336 the same as $? when the pragma "use vmsish 'status'" is in
1337 effect.
1338
1339 This variable was added in Perl 5.8.9.
1340
1341 $EXTENDED_OS_ERROR
1342 $^E Error information specific to the current operating system. At
1343 the moment, this differs from $! under only VMS, OS/2, and
1344 Win32 (and for MacPerl). On all other platforms, $^E is always
1345 just the same as $!.
1346
1347 Under VMS, $^E provides the VMS status value from the last
1348 system error. This is more specific information about the last
1349 system error than that provided by $!. This is particularly
1350 important when $! is set to EVMSERR.
1351
1352 Under OS/2, $^E is set to the error code of the last call to
1353 OS/2 API either via CRT, or directly from perl.
1354
1355 Under Win32, $^E always returns the last error information
1356 reported by the Win32 call "GetLastError()" which describes the
1357 last error from within the Win32 API. Most Win32-specific code
1358 will report errors via $^E. ANSI C and Unix-like calls set
1359 "errno" and so most portable Perl code will report errors via
1360 $!.
1361
1362 Caveats mentioned in the description of $! generally apply to
1363 $^E, also.
1364
1365 This variable was added in Perl 5.003.
1366
1367 Mnemonic: Extra error explanation.
1368
1369 $EXCEPTIONS_BEING_CAUGHT
1370 $^S Current state of the interpreter.
1371
1372 $^S State
1373 --------- -------------------
1374 undef Parsing module/eval
1375 true (1) Executing an eval
1376 false (0) Otherwise
1377
1378 The first state may happen in $SIG{__DIE__} and $SIG{__WARN__}
1379 handlers.
1380
1381 This variable was added in Perl 5.004.
1382
1383 $WARNING
1384 $^W The current value of the warning switch, initially true if -w
1385 was used, false otherwise, but directly modifiable.
1386
1387 See also warnings.
1388
1389 Mnemonic: related to the -w switch.
1390
1391 ${^WARNING_BITS}
1392 The current set of warning checks enabled by the "use warnings"
1393 pragma. It has the same scoping as the $^H and "%^H"
1394 variables. The exact values are considered internal to the
1395 warnings pragma and may change between versions of Perl.
1396
1397 This variable was added in Perl 5.6.
1398
1399 $OS_ERROR
1400 $ERRNO
1401 $! When referenced, $! retrieves the current value of the C
1402 "errno" integer variable. If $! is assigned a numerical value,
1403 that value is stored in "errno". When referenced as a string,
1404 $! yields the system error string corresponding to "errno".
1405
1406 Many system or library calls set "errno" if they fail, to
1407 indicate the cause of failure. They usually do not set "errno"
1408 to zero if they succeed. This means "errno", hence $!, is
1409 meaningful only immediately after a failure:
1410
1411 if (open my $fh, "<", $filename) {
1412 # Here $! is meaningless.
1413 ...
1414 }
1415 else {
1416 # ONLY here is $! meaningful.
1417 ...
1418 # Already here $! might be meaningless.
1419 }
1420 # Since here we might have either success or failure,
1421 # $! is meaningless.
1422
1423 Here, meaningless means that $! may be unrelated to the outcome
1424 of the "open()" operator. Assignment to $! is similarly
1425 ephemeral. It can be used immediately before invoking the
1426 "die()" operator, to set the exit value, or to inspect the
1427 system error string corresponding to error n, or to restore $!
1428 to a meaningful state.
1429
1430 Mnemonic: What just went bang?
1431
1432 %OS_ERROR
1433 %ERRNO
1434 %! Each element of "%!" has a true value only if $! is set to that
1435 value. For example, $!{ENOENT} is true if and only if the
1436 current value of $! is "ENOENT"; that is, if the most recent
1437 error was "No such file or directory" (or its moral equivalent:
1438 not all operating systems give that exact error, and certainly
1439 not all languages). To check if a particular key is meaningful
1440 on your system, use "exists $!{the_key}"; for a list of legal
1441 keys, use "keys %!". See Errno for more information, and also
1442 see "$!".
1443
1444 This variable was added in Perl 5.005.
1445
1446 $CHILD_ERROR
1447 $? The status returned by the last pipe close, backtick ("``")
1448 command, successful call to "wait()" or "waitpid()", or from
1449 the "system()" operator. This is just the 16-bit status word
1450 returned by the traditional Unix "wait()" system call (or else
1451 is made up to look like it). Thus, the exit value of the
1452 subprocess is really ("$? >> 8"), and "$? & 127" gives which
1453 signal, if any, the process died from, and "$? & 128" reports
1454 whether there was a core dump.
1455
1456 Additionally, if the "h_errno" variable is supported in C, its
1457 value is returned via $? if any "gethost*()" function fails.
1458
1459 If you have installed a signal handler for "SIGCHLD", the value
1460 of $? will usually be wrong outside that handler.
1461
1462 Inside an "END" subroutine $? contains the value that is going
1463 to be given to "exit()". You can modify $? in an "END"
1464 subroutine to change the exit status of your program. For
1465 example:
1466
1467 END {
1468 $? = 1 if $? == 255; # die would make it 255
1469 }
1470
1471 Under VMS, the pragma "use vmsish 'status'" makes $? reflect
1472 the actual VMS exit status, instead of the default emulation of
1473 POSIX status; see "$?" in perlvms for details.
1474
1475 Mnemonic: similar to sh and ksh.
1476
1477 $EVAL_ERROR
1478 $@ The Perl syntax error message from the last "eval()" operator.
1479 If $@ is the null string, the last "eval()" parsed and executed
1480 correctly (although the operations you invoked may have failed
1481 in the normal fashion).
1482
1483 Warning messages are not collected in this variable. You can,
1484 however, set up a routine to process warnings by setting
1485 $SIG{__WARN__} as described in "%SIG".
1486
1487 Mnemonic: Where was the syntax error "at"?
1488
1489 Variables related to the interpreter state
1490 These variables provide information about the current interpreter
1491 state.
1492
1493 $COMPILING
1494 $^C The current value of the flag associated with the -c switch.
1495 Mainly of use with -MO=... to allow code to alter its behavior
1496 when being compiled, such as for example to "AUTOLOAD" at
1497 compile time rather than normal, deferred loading. Setting
1498 "$^C = 1" is similar to calling "B::minus_c".
1499
1500 This variable was added in Perl 5.6.
1501
1502 $DEBUGGING
1503 $^D The current value of the debugging flags. May be read or set.
1504 Like its command-line equivalent, you can use numeric or
1505 symbolic values, eg "$^D = 10" or "$^D = "st"".
1506
1507 Mnemonic: value of -D switch.
1508
1509 ${^ENCODING}
1510 The object reference to the "Encode" object that is used to
1511 convert the source code to Unicode. Thanks to this variable
1512 your Perl script does not have to be written in UTF-8. Default
1513 is undef. The direct manipulation of this variable is highly
1514 discouraged.
1515
1516 This variable was added in Perl 5.8.2.
1517
1518 ${^GLOBAL_PHASE}
1519 The current phase of the perl interpreter.
1520
1521 Possible values are:
1522
1523 CONSTRUCT
1524 The "PerlInterpreter*" is being constructed via
1525 "perl_construct". This value is mostly there for
1526 completeness and for use via the underlying C variable
1527 "PL_phase". It's not really possible for Perl code to
1528 be executed unless construction of the interpreter is
1529 finished.
1530
1531 START This is the global compile-time. That includes,
1532 basically, every "BEGIN" block executed directly or
1533 indirectly from during the compile-time of the top-
1534 level program.
1535
1536 This phase is not called "BEGIN" to avoid confusion
1537 with "BEGIN"-blocks, as those are executed during
1538 compile-time of any compilation unit, not just the top-
1539 level program. A new, localised compile-time entered
1540 at run-time, for example by constructs as "eval "use
1541 SomeModule"" are not global interpreter phases, and
1542 therefore aren't reflected by "${^GLOBAL_PHASE}".
1543
1544 CHECK Execution of any "CHECK" blocks.
1545
1546 INIT Similar to "CHECK", but for "INIT"-blocks, not "CHECK"
1547 blocks.
1548
1549 RUN The main run-time, i.e. the execution of
1550 "PL_main_root".
1551
1552 END Execution of any "END" blocks.
1553
1554 DESTRUCT
1555 Global destruction.
1556
1557 Also note that there's no value for UNITCHECK-blocks. That's
1558 because those are run for each compilation unit individually,
1559 and therefore is not a global interpreter phase.
1560
1561 Not every program has to go through each of the possible
1562 phases, but transition from one phase to another can only
1563 happen in the order described in the above list.
1564
1565 An example of all of the phases Perl code can see:
1566
1567 BEGIN { print "compile-time: ${^GLOBAL_PHASE}\n" }
1568
1569 INIT { print "init-time: ${^GLOBAL_PHASE}\n" }
1570
1571 CHECK { print "check-time: ${^GLOBAL_PHASE}\n" }
1572
1573 {
1574 package Print::Phase;
1575
1576 sub new {
1577 my ($class, $time) = @_;
1578 return bless \$time, $class;
1579 }
1580
1581 sub DESTROY {
1582 my $self = shift;
1583 print "$$self: ${^GLOBAL_PHASE}\n";
1584 }
1585 }
1586
1587 print "run-time: ${^GLOBAL_PHASE}\n";
1588
1589 my $runtime = Print::Phase->new(
1590 "lexical variables are garbage collected before END"
1591 );
1592
1593 END { print "end-time: ${^GLOBAL_PHASE}\n" }
1594
1595 our $destruct = Print::Phase->new(
1596 "package variables are garbage collected after END"
1597 );
1598
1599 This will print out
1600
1601 compile-time: START
1602 check-time: CHECK
1603 init-time: INIT
1604 run-time: RUN
1605 lexical variables are garbage collected before END: RUN
1606 end-time: END
1607 package variables are garbage collected after END: DESTRUCT
1608
1609 This variable was added in Perl 5.14.0.
1610
1611 $^H WARNING: This variable is strictly for internal use only. Its
1612 availability, behavior, and contents are subject to change
1613 without notice.
1614
1615 This variable contains compile-time hints for the Perl
1616 interpreter. At the end of compilation of a BLOCK the value of
1617 this variable is restored to the value when the interpreter
1618 started to compile the BLOCK.
1619
1620 When perl begins to parse any block construct that provides a
1621 lexical scope (e.g., eval body, required file, subroutine body,
1622 loop body, or conditional block), the existing value of $^H is
1623 saved, but its value is left unchanged. When the compilation
1624 of the block is completed, it regains the saved value. Between
1625 the points where its value is saved and restored, code that
1626 executes within BEGIN blocks is free to change the value of
1627 $^H.
1628
1629 This behavior provides the semantic of lexical scoping, and is
1630 used in, for instance, the "use strict" pragma.
1631
1632 The contents should be an integer; different bits of it are
1633 used for different pragmatic flags. Here's an example:
1634
1635 sub add_100 { $^H |= 0x100 }
1636
1637 sub foo {
1638 BEGIN { add_100() }
1639 bar->baz($boon);
1640 }
1641
1642 Consider what happens during execution of the BEGIN block. At
1643 this point the BEGIN block has already been compiled, but the
1644 body of "foo()" is still being compiled. The new value of $^H
1645 will therefore be visible only while the body of "foo()" is
1646 being compiled.
1647
1648 Substitution of "BEGIN { add_100() }" block with:
1649
1650 BEGIN { require strict; strict->import('vars') }
1651
1652 demonstrates how "use strict 'vars'" is implemented. Here's a
1653 conditional version of the same lexical pragma:
1654
1655 BEGIN {
1656 require strict; strict->import('vars') if $condition
1657 }
1658
1659 This variable was added in Perl 5.003.
1660
1661 %^H The "%^H" hash provides the same scoping semantic as $^H. This
1662 makes it useful for implementation of lexically scoped pragmas.
1663 See perlpragma.
1664
1665 When putting items into "%^H", in order to avoid conflicting
1666 with other users of the hash there is a convention regarding
1667 which keys to use. A module should use only keys that begin
1668 with the module's name (the name of its main package) and a "/"
1669 character. For example, a module "Foo::Bar" should use keys
1670 such as "Foo::Bar/baz".
1671
1672 This variable was added in Perl 5.6.
1673
1674 ${^OPEN}
1675 An internal variable used by PerlIO. A string in two parts,
1676 separated by a "\0" byte, the first part describes the input
1677 layers, the second part describes the output layers.
1678
1679 This variable was added in Perl 5.8.0.
1680
1681 $PERLDB
1682 $^P The internal variable for debugging support. The meanings of
1683 the various bits are subject to change, but currently indicate:
1684
1685 0x01 Debug subroutine enter/exit.
1686
1687 0x02 Line-by-line debugging. Causes "DB::DB()" subroutine to
1688 be called for each statement executed. Also causes
1689 saving source code lines (like 0x400).
1690
1691 0x04 Switch off optimizations.
1692
1693 0x08 Preserve more data for future interactive inspections.
1694
1695 0x10 Keep info about source lines on which a subroutine is
1696 defined.
1697
1698 0x20 Start with single-step on.
1699
1700 0x40 Use subroutine address instead of name when reporting.
1701
1702 0x80 Report "goto &subroutine" as well.
1703
1704 0x100 Provide informative "file" names for evals based on the
1705 place they were compiled.
1706
1707 0x200 Provide informative names to anonymous subroutines based
1708 on the place they were compiled.
1709
1710 0x400 Save source code lines into "@{"_<$filename"}".
1711
1712 Some bits may be relevant at compile-time only, some at run-
1713 time only. This is a new mechanism and the details may change.
1714 See also perldebguts.
1715
1716 ${^TAINT}
1717 Reflects if taint mode is on or off. 1 for on (the program was
1718 run with -T), 0 for off, -1 when only taint warnings are
1719 enabled (i.e. with -t or -TU).
1720
1721 This variable is read-only.
1722
1723 This variable was added in Perl 5.8.
1724
1725 ${^UNICODE}
1726 Reflects certain Unicode settings of Perl. See perlrun
1727 documentation for the "-C" switch for more information about
1728 the possible values.
1729
1730 This variable is set during Perl startup and is thereafter
1731 read-only.
1732
1733 This variable was added in Perl 5.8.2.
1734
1735 ${^UTF8CACHE}
1736 This variable controls the state of the internal UTF-8 offset
1737 caching code. 1 for on (the default), 0 for off, -1 to debug
1738 the caching code by checking all its results against linear
1739 scans, and panicking on any discrepancy.
1740
1741 This variable was added in Perl 5.8.9.
1742
1743 ${^UTF8LOCALE}
1744 This variable indicates whether a UTF-8 locale was detected by
1745 perl at startup. This information is used by perl when it's in
1746 adjust-utf8ness-to-locale mode (as when run with the "-CL"
1747 command-line switch); see perlrun for more info on this.
1748
1749 This variable was added in Perl 5.8.8.
1750
1751 Deprecated and removed variables
1752 Deprecating a variable announces the intent of the perl maintainers to
1753 eventually remove the variable from the language. It may still be
1754 available despite its status. Using a deprecated variable triggers a
1755 warning.
1756
1757 Once a variable is removed, its use triggers an error telling you the
1758 variable is unsupported.
1759
1760 See perldiag for details about error messages.
1761
1762 $OFMT
1763 $# $# was a variable that could be used to format printed numbers.
1764 After a deprecation cycle, its magic was removed in Perl 5.10
1765 and using it now triggers a warning: "$# is no longer
1766 supported".
1767
1768 This is not the sigil you use in front of an array name to get
1769 the last index, like $#array. That's still how you get the
1770 last index of an array in Perl. The two have nothing to do
1771 with each other.
1772
1773 Deprecated in Perl 5.
1774
1775 Removed in Perl 5.10.
1776
1777 $* $* was a variable that you could use to enable multiline
1778 matching. After a deprecation cycle, its magic was removed in
1779 Perl 5.10. Using it now triggers a warning: "$* is no longer
1780 supported". You should use the "/s" and "/m" regexp modifiers
1781 instead.
1782
1783 Deprecated in Perl 5.
1784
1785 Removed in Perl 5.10.
1786
1787 $ARRAY_BASE
1788 $[ This variable stores the index of the first element in an
1789 array, and of the first character in a substring. The default
1790 is 0, but you could theoretically set it to 1 to make Perl
1791 behave more like awk (or Fortran) when subscripting and when
1792 evaluating the index() and substr() functions.
1793
1794 As of release 5 of Perl, assignment to $[ is treated as a
1795 compiler directive, and cannot influence the behavior of any
1796 other file. (That's why you can only assign compile-time
1797 constants to it.) Its use is highly discouraged.
1798
1799 Prior to Perl 5.10, assignment to $[ could be seen from outer
1800 lexical scopes in the same file, unlike other compile-time
1801 directives (such as strict). Using local() on it would bind
1802 its value strictly to a lexical block. Now it is always
1803 lexically scoped.
1804
1805 As of Perl 5.16, it is implemented by the arybase module. See
1806 arybase for more details on its behaviour.
1807
1808 Under "use v5.16", or "no feature "array_base"", $[ no longer
1809 has any effect, and always contains 0. Assigning 0 to it is
1810 permitted, but any other value will produce an error.
1811
1812 Mnemonic: [ begins subscripts.
1813
1814 Deprecated in Perl 5.12.
1815
1816 $OLD_PERL_VERSION
1817 $] See "$^V" for a more modern representation of the Perl version
1818 that allows accurate string comparisons.
1819
1820 The version + patchlevel / 1000 of the Perl interpreter. This
1821 variable can be used to determine whether the Perl interpreter
1822 executing a script is in the right range of versions:
1823
1824 warn "No checksumming!\n" if $] < 3.019;
1825
1826 The floating point representation can sometimes lead to
1827 inaccurate numeric comparisons.
1828
1829 See also the documentation of "use VERSION" and "require
1830 VERSION" for a convenient way to fail if the running Perl
1831 interpreter is too old.
1832
1833 Mnemonic: Is this version of perl in the right bracket?
1834
1835
1836
1837perl v5.16.3 2013-03-04 PERLVAR(1)