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. A Unicode letter that is not ASCII
16 is not considered to be a letter unless "use utf8" is in effect, and
17 somewhat more complicated rules apply; see "Identifier parsing" in
18 perldata for details.
19
20 Perl variable names may also be a sequence of digits, a single
21 punctuation character, or the two-character sequence: "^" (caret or
22 CIRCUMFLEX ACCENT) followed by any one of the characters "[][A-Z^_?\]".
23 These names are all reserved for special uses by Perl; for example, the
24 all-digits names are used to hold data captured by backreferences after
25 a regular expression match.
26
27 Since Perl v5.6.0, Perl variable names may also be alphanumeric strings
28 preceded by a caret. These must all be written using the demarcated
29 variable form using curly braces such as "${^Foo}"; the braces are not
30 optional. "${^Foo}" denotes the scalar variable whose name is
31 considered to be a control-"F" followed by two "o"'s. (See "Demarcated
32 variable names using braces" in perldata for more information on this
33 form of spelling a variable name or specifying access to an element of
34 an array or a hash). These variables are reserved for future special
35 uses by Perl, except for the ones that begin with "^_" (caret-
36 underscore). No name that begins with "^_" will acquire a special
37 meaning in any future version of Perl; such names may therefore be used
38 safely in programs. $^_ itself, however, is reserved.
39
40 Note that you also must use the demarcated form to access subscripts of
41 variables of this type when interpolating, for instance to access the
42 first element of the "@{^CAPTURE}" variable inside of a double quoted
43 string you would write "${^CAPTURE[0]}" and NOT "${^CAPTURE}[0]" which
44 would mean to reference a scalar variable named "${^CAPTURE}" and not
45 index 0 of the magic "@{^CAPTURE}" array which is populated by the
46 regex engine.
47
48 Perl identifiers that begin with digits or punctuation characters are
49 exempt from the effects of the "package" declaration and are always
50 forced to be in package "main"; they are also exempt from "strict
51 'vars'" errors. A few other names are also exempt in these ways:
52
53 ENV STDIN
54 INC STDOUT
55 ARGV STDERR
56 ARGVOUT
57 SIG
58
59 In particular, the special "${^_XYZ}" variables are always taken to be
60 in package "main", regardless of any "package" declarations presently
61 in scope.
62
64 The following names have special meaning to Perl. Most punctuation
65 names have reasonable mnemonics, or analogs in the shells.
66 Nevertheless, if you wish to use long variable names, you need only
67 say:
68
69 use English;
70
71 at the top of your program. This aliases all the short names to the
72 long names in the current package. Some even have medium names,
73 generally borrowed from awk. For more info, please see English.
74
75 Before you continue, note the sort order for variables. In general, we
76 first list the variables in case-insensitive, almost-lexigraphical
77 order (ignoring the "{" or "^" preceding words, as in "${^UNICODE}" or
78 $^T), although $_ and @_ move up to the top of the pile. For variables
79 with the same identifier, we list it in order of scalar, array, hash,
80 and bareword.
81
82 General Variables
83 $ARG
84 $_ The default input and pattern-searching space. The following
85 pairs are equivalent:
86
87 while (<>) {...} # equivalent only in while!
88 while (defined($_ = <>)) {...}
89
90 /^Subject:/
91 $_ =~ /^Subject:/
92
93 tr/a-z/A-Z/
94 $_ =~ tr/a-z/A-Z/
95
96 chomp
97 chomp($_)
98
99 Here are the places where Perl will assume $_ even if you don't
100 use it:
101
102 • The following functions use $_ as a default argument:
103
104 abs, alarm, chomp, chop, chr, chroot, cos, defined, eval,
105 evalbytes, exp, fc, glob, hex, int, lc, lcfirst, length,
106 log, lstat, mkdir, oct, ord, pos, print, printf, quotemeta,
107 readlink, readpipe, ref, require, reverse (in scalar context
108 only), rmdir, say, sin, split (for its second argument),
109 sqrt, stat, study, uc, ucfirst, unlink, unpack.
110
111 • All file tests ("-f", "-d") except for "-t", which defaults
112 to STDIN. See "-X" in perlfunc
113
114 • The pattern matching operations "m//", "s///" and "tr///"
115 (aka "y///") when used without an "=~" operator.
116
117 • The default iterator variable in a "foreach" loop if no
118 other variable is supplied.
119
120 • The implicit iterator variable in the grep() and map()
121 functions.
122
123 • The implicit variable of given().
124
125 • The default place to put the next value or input record when
126 a "<FH>", "readline", "readdir" or "each" operation's result
127 is tested by itself as the sole criterion of a "while" test.
128 Outside a "while" test, this will not happen.
129
130 $_ is a global variable.
131
132 However, between perl v5.10.0 and v5.24.0, it could be used
133 lexically by writing "my $_". Making $_ refer to the global $_
134 in the same scope was then possible with "our $_". This
135 experimental feature was removed and is now a fatal error, but
136 you may encounter it in older code.
137
138 Mnemonic: underline is understood in certain operations.
139
140 @ARG
141 @_ Within a subroutine the array @_ contains the parameters passed
142 to that subroutine. Inside a subroutine, @_ is the default
143 array for the array operators "pop" and "shift".
144
145 See perlsub.
146
147 $LIST_SEPARATOR
148 $" When an array or an array slice is interpolated into a double-
149 quoted string or a similar context such as "/.../", its
150 elements are separated by this value. Default is a space. For
151 example, this:
152
153 print "The array is: @array\n";
154
155 is equivalent to this:
156
157 print "The array is: " . join($", @array) . "\n";
158
159 Mnemonic: works in double-quoted context.
160
161 $PROCESS_ID
162 $PID
163 $$ The process number of the Perl running this script. Though you
164 can set this variable, doing so is generally discouraged,
165 although it can be invaluable for some testing purposes. It
166 will be reset automatically across fork() calls.
167
168 Note for Linux and Debian GNU/kFreeBSD users: Before Perl
169 v5.16.0 perl would emulate POSIX semantics on Linux systems
170 using LinuxThreads, a partial implementation of POSIX Threads
171 that has since been superseded by the Native POSIX Thread
172 Library (NPTL).
173
174 LinuxThreads is now obsolete on Linux, and caching getpid()
175 like this made embedding perl unnecessarily complex (since
176 you'd have to manually update the value of $$), so now $$ and
177 getppid() will always return the same values as the underlying
178 C library.
179
180 Debian GNU/kFreeBSD systems also used LinuxThreads up until and
181 including the 6.0 release, but after that moved to FreeBSD
182 thread semantics, which are POSIX-like.
183
184 To see if your system is affected by this discrepancy check if
185 "getconf GNU_LIBPTHREAD_VERSION | grep -q NPTL" returns a false
186 value. NTPL threads preserve the POSIX semantics.
187
188 Mnemonic: same as shells.
189
190 $PROGRAM_NAME
191 $0 Contains the name of the program being executed.
192
193 On some (but not all) operating systems assigning to $0
194 modifies the argument area that the "ps" program sees. On some
195 platforms you may have to use special "ps" options or a
196 different "ps" to see the changes. Modifying the $0 is more
197 useful as a way of indicating the current program state than it
198 is for hiding the program you're running.
199
200 Note that there are platform-specific limitations on the
201 maximum length of $0. In the most extreme case it may be
202 limited to the space occupied by the original $0.
203
204 In some platforms there may be arbitrary amount of padding, for
205 example space characters, after the modified name as shown by
206 "ps". In some platforms this padding may extend all the way to
207 the original length of the argument area, no matter what you do
208 (this is the case for example with Linux 2.2).
209
210 Note for BSD users: setting $0 does not completely remove
211 "perl" from the ps(1) output. For example, setting $0 to
212 "foobar" may result in "perl: foobar (perl)" (whether both the
213 "perl: " prefix and the " (perl)" suffix are shown depends on
214 your exact BSD variant and version). This is an operating
215 system feature, Perl cannot help it.
216
217 In multithreaded scripts Perl coordinates the threads so that
218 any thread may modify its copy of the $0 and the change becomes
219 visible to ps(1) (assuming the operating system plays along).
220 Note that the view of $0 the other threads have will not change
221 since they have their own copies of it.
222
223 If the program has been given to perl via the switches "-e" or
224 "-E", $0 will contain the string "-e".
225
226 On Linux as of perl v5.14.0 the legacy process name will be set
227 with prctl(2), in addition to altering the POSIX name via
228 "argv[0]" as perl has done since version 4.000. Now system
229 utilities that read the legacy process name such as ps, top and
230 killall will recognize the name you set when assigning to $0.
231 The string you supply will be cut off at 16 bytes, this is a
232 limitation imposed by Linux.
233
234 Wide characters are invalid in $0 values. For historical
235 reasons, though, Perl accepts them and encodes them to UTF-8.
236 When this happens a wide-character warning is triggered.
237
238 Mnemonic: same as sh and ksh.
239
240 $REAL_GROUP_ID
241 $GID
242 $( The real gid of this process. If you are on a machine that
243 supports membership in multiple groups simultaneously, gives a
244 space separated list of groups you are in. The first number is
245 the one returned by getgid(), and the subsequent ones by
246 getgroups(), one of which may be the same as the first number.
247
248 However, a value assigned to $( must be a single number used to
249 set the real gid. So the value given by $( should not be
250 assigned back to $( without being forced numeric, such as by
251 adding zero. Note that this is different to the effective gid
252 ($)) which does take a list.
253
254 You can change both the real gid and the effective gid at the
255 same time by using POSIX::setgid(). Changes to $( require a
256 check to $! to detect any possible errors after an attempted
257 change.
258
259 Mnemonic: parentheses are used to group things. The real gid
260 is the group you left, if you're running setgid.
261
262 $EFFECTIVE_GROUP_ID
263 $EGID
264 $) The effective gid of this process. If you are on a machine
265 that supports membership in multiple groups simultaneously,
266 gives a space separated list of groups you are in. The first
267 number is the one returned by getegid(), and the subsequent
268 ones by getgroups(), one of which may be the same as the first
269 number.
270
271 Similarly, a value assigned to $) must also be a space-
272 separated list of numbers. The first number sets the effective
273 gid, and the rest (if any) are passed to setgroups(). To get
274 the effect of an empty list for setgroups(), just repeat the
275 new effective gid; that is, to force an effective gid of 5 and
276 an effectively empty setgroups() list, say " $) = "5 5" ".
277
278 You can change both the effective gid and the real gid at the
279 same time by using POSIX::setgid() (use only a single numeric
280 argument). Changes to $) require a check to $! to detect any
281 possible errors after an attempted change.
282
283 $<, $>, $( and $) can be set only on machines that support the
284 corresponding set[re][ug]id() routine. $( and $) can be
285 swapped only on machines supporting setregid().
286
287 Mnemonic: parentheses are used to group things. The effective
288 gid is the group that's right for you, if you're running
289 setgid.
290
291 $REAL_USER_ID
292 $UID
293 $< The real uid of this process. You can change both the real uid
294 and the effective uid at the same time by using
295 POSIX::setuid(). Since changes to $< require a system call,
296 check $! after a change attempt to detect any possible errors.
297
298 Mnemonic: it's the uid you came from, if you're running setuid.
299
300 $EFFECTIVE_USER_ID
301 $EUID
302 $> The effective uid of this process. For example:
303
304 $< = $>; # set real to effective uid
305 ($<,$>) = ($>,$<); # swap real and effective uids
306
307 You can change both the effective uid and the real uid at the
308 same time by using POSIX::setuid(). Changes to $> require a
309 check to $! to detect any possible errors after an attempted
310 change.
311
312 $< and $> can be swapped only on machines supporting
313 setreuid().
314
315 Mnemonic: it's the uid you went to, if you're running setuid.
316
317 $SUBSCRIPT_SEPARATOR
318 $SUBSEP
319 $; The subscript separator for multidimensional array emulation.
320 If you refer to a hash element as
321
322 $foo{$x,$y,$z}
323
324 it really means
325
326 $foo{join($;, $x, $y, $z)}
327
328 But don't put
329
330 @foo{$x,$y,$z} # a slice--note the @
331
332 which means
333
334 ($foo{$x},$foo{$y},$foo{$z})
335
336 Default is "\034", the same as SUBSEP in awk. If your keys
337 contain binary data there might not be any safe value for $;.
338
339 Consider using "real" multidimensional arrays as described in
340 perllol.
341
342 Mnemonic: comma (the syntactic subscript separator) is a semi-
343 semicolon.
344
345 $a
346 $b Special package variables when using sort(), see "sort" in
347 perlfunc. Because of this specialness $a and $b don't need to
348 be declared (using "use vars", or our()) even when using the
349 "strict 'vars'" pragma. Don't lexicalize them with "my $a" or
350 "my $b" if you want to be able to use them in the sort()
351 comparison block or function.
352
353 %ENV The hash %ENV contains your current environment. Setting a
354 value in "ENV" changes the environment for any child processes
355 you subsequently fork() off.
356
357 As of v5.18.0, both keys and values stored in %ENV are
358 stringified.
359
360 my $foo = 1;
361 $ENV{'bar'} = \$foo;
362 if( ref $ENV{'bar'} ) {
363 say "Pre 5.18.0 Behaviour";
364 } else {
365 say "Post 5.18.0 Behaviour";
366 }
367
368 Previously, only child processes received stringified values:
369
370 my $foo = 1;
371 $ENV{'bar'} = \$foo;
372
373 # Always printed 'non ref'
374 system($^X, '-e',
375 q/print ( ref $ENV{'bar'} ? 'ref' : 'non ref' ) /);
376
377 This happens because you can't really share arbitrary data
378 structures with foreign processes.
379
380 $OLD_PERL_VERSION
381 $] The revision, version, and subversion of the Perl interpreter,
382 represented as a decimal of the form 5.XXXYYY, where XXX is the
383 version / 1e3 and YYY is the subversion / 1e6. For example,
384 Perl v5.10.1 would be "5.010001".
385
386 This variable can be used to determine whether the Perl
387 interpreter executing a script is in the right range of
388 versions:
389
390 warn "No PerlIO!\n" if "$]" < 5.008;
391
392 When comparing $], numeric comparison operators should be used,
393 but the variable should be stringified first to avoid issues
394 where its original numeric value is inaccurate.
395
396 See also the documentation of "use VERSION" and "require
397 VERSION" for a convenient way to fail if the running Perl
398 interpreter is too old.
399
400 See "$^V" for a representation of the Perl version as a version
401 object, which allows more flexible string comparisons.
402
403 The main advantage of $] over $^V is that it works the same on
404 any version of Perl. The disadvantages are that it can't
405 easily be compared to versions in other formats (e.g. literal
406 v-strings, "v1.2.3" or version objects) and numeric comparisons
407 are subject to the binary floating point representation; it's
408 good for numeric literal version checks and bad for comparing
409 to a variable that hasn't been sanity-checked.
410
411 The $OLD_PERL_VERSION form was added in Perl v5.20.0 for
412 historical reasons but its use is discouraged. (If your reason
413 to use $] is to run code on old perls then referring to it as
414 $OLD_PERL_VERSION would be self-defeating.)
415
416 Mnemonic: Is this version of perl in the right bracket?
417
418 $SYSTEM_FD_MAX
419 $^F The maximum system file descriptor, ordinarily 2. System file
420 descriptors are passed to exec()ed processes, while higher file
421 descriptors are not. Also, during an open(), system file
422 descriptors are preserved even if the open() fails (ordinary
423 file descriptors are closed before the open() is attempted).
424 The close-on-exec status of a file descriptor will be decided
425 according to the value of $^F when the corresponding file,
426 pipe, or socket was opened, not the time of the exec().
427
428 @F The array @F contains the fields of each line read in when
429 autosplit mode is turned on. See perlrun for the -a switch.
430 This array is package-specific, and must be declared or given a
431 full package name if not in package main when running under
432 "strict 'vars'".
433
434 @INC The array @INC contains the list of places that the "do EXPR",
435 "require", or "use" constructs look for their library files.
436 It initially consists of the arguments to any -I command-line
437 switches, followed by the default Perl library, probably
438 /usr/local/lib/perl. Prior to Perl 5.26, "." -which represents
439 the current directory, was included in @INC; it has been
440 removed. This change in behavior is documented in
441 "PERL_USE_UNSAFE_INC" and it is not recommended that "." be re-
442 added to @INC. If you need to modify @INC at runtime, you
443 should use the "use lib" pragma to get the machine-dependent
444 library properly loaded as well:
445
446 use lib '/mypath/libdir/';
447 use SomeMod;
448
449 You can also insert hooks into the file inclusion system by
450 putting Perl code directly into @INC. Those hooks may be
451 subroutine references, array references or blessed objects.
452 See "require" in perlfunc for details.
453
454 %INC The hash %INC contains entries for each filename included via
455 the "do", "require", or "use" operators. The key is the
456 filename you specified (with module names converted to
457 pathnames), and the value is the location of the file found.
458 The "require" operator uses this hash to determine whether a
459 particular file has already been included.
460
461 If the file was loaded via a hook (e.g. a subroutine reference,
462 see "require" in perlfunc for a description of these hooks),
463 this hook is by default inserted into %INC in place of a
464 filename. Note, however, that the hook may have set the %INC
465 entry by itself to provide some more specific info.
466
467 $INC As of 5.37.7 when an @INC hook is executed the index of the
468 @INC array that holds the hook will be localized into the $INC
469 variable. When the hook returns the integer successor of its
470 value will be used to determine the next index in @INC that
471 will be checked, thus if it is set to -1 (or "undef") the
472 traversal over the @INC array will be restarted from its
473 beginning.
474
475 Normally traversal through the @INC array is from beginning to
476 end ("0 .. $#INC"), and if the @INC array is modified by the
477 hook the iterator may be left in a state where newly added
478 entries are skipped. Changing this value allows an @INC hook
479 to rewrite the @INC array and tell Perl where to continue
480 afterwards. See "require" in perlfunc for details on @INC
481 hooks.
482
483 $INPLACE_EDIT
484 $^I The current value of the inplace-edit extension. Use "undef"
485 to disable inplace editing.
486
487 Mnemonic: value of -i switch.
488
489 @ISA Each package contains a special array called @ISA which
490 contains a list of that class's parent classes, if any. This
491 array is simply a list of scalars, each of which is a string
492 that corresponds to a package name. The array is examined when
493 Perl does method resolution, which is covered in perlobj.
494
495 To load packages while adding them to @ISA, see the parent
496 pragma. The discouraged base pragma does this as well, but
497 should not be used except when compatibility with the
498 discouraged fields pragma is required.
499
500 $^M By default, running out of memory is an untrappable, fatal
501 error. However, if suitably built, Perl can use the contents
502 of $^M as an emergency memory pool after die()ing. Suppose
503 that your Perl were compiled with "-DPERL_EMERGENCY_SBRK" and
504 used Perl's malloc. Then
505
506 $^M = 'a' x (1 << 16);
507
508 would allocate a 64K buffer for use in an emergency. See the
509 INSTALL file in the Perl distribution for information on how to
510 add custom C compilation flags when compiling perl. To
511 discourage casual use of this advanced feature, there is no
512 English long name for this variable.
513
514 This variable was added in Perl 5.004.
515
516 ${^MAX_NESTED_EVAL_BEGIN_BLOCKS}
517 This variable determines the maximum number "eval EXPR"/"BEGIN"
518 or "require"/"BEGIN" block nesting that is allowed. This means
519 it also controls the maximum nesting of "use" statements as
520 well.
521
522 The default of 1000 should be sufficiently large for normal
523 working purposes, and if you must raise it then you should be
524 conservative with your choice or you may encounter segfaults
525 from exhaustion of the C stack. It seems unlikely that real
526 code has a use depth above 1000, but we have left this
527 configurable just in case.
528
529 When set to 0 then "BEGIN" blocks inside of "eval EXPR" or
530 "require EXPR" are forbidden entirely and will trigger an
531 exception which will terminate the compilation and in the case
532 of "require" will throw an exception, or in the case of "eval"
533 return the error in $@ as usual.
534
535 Consider the code
536
537 perl -le'sub f { eval "BEGIN { f() }"; } f()'
538
539 each invocation of f() will consume considerable C stack, and
540 this variable is used to cause code like this to die instead of
541 exhausting the C stack and triggering a segfault. Needless to
542 say code like this is unusual, it is unlikely you will actually
543 need to raise the setting. However it may be useful to set it
544 to 0 for a limited time period to prevent BEGIN{} blocks from
545 being executed during an "eval EXPR".
546
547 Note that setting this to 1 would NOT affect code like this:
548
549 BEGIN { $n += 1; BEGIN { $n += 2; BEGIN { $n += 4 } } }
550
551 The reason is that BEGIN blocks are executed immediately after
552 they are completed, thus the innermost will execute before the
553 ones which contain it have even finished compiling, and the
554 depth will not go above 1. In fact the above code is equivalent
555 to
556
557 BEGIN { $n+=4 }
558 BEGIN { $n+=2 }
559 BEGIN { $n+=1 }
560
561 which makes it obvious why a ${^MAX_EVAL_BEGIN_DEPTH} of 1
562 would not block this code.
563
564 Only "BEGIN"'s executed inside of an "eval" or "require"
565 (possibly via "use") are affected.
566
567 $OSNAME
568 $^O The name of the operating system under which this copy of Perl
569 was built, as determined during the configuration process. For
570 examples see "PLATFORMS" in perlport.
571
572 The value is identical to $Config{'osname'}. See also Config
573 and the -V command-line switch documented in perlrun.
574
575 In Windows platforms, $^O is not very helpful: since it is
576 always "MSWin32", it doesn't tell the difference between
577 95/98/ME/NT/2000/XP/CE/.NET. Use Win32::GetOSName() or
578 Win32::GetOSVersion() (see Win32 and perlport) to distinguish
579 between the variants.
580
581 This variable was added in Perl 5.003.
582
583 %SIG The hash %SIG contains signal handlers for signals. For
584 example:
585
586 sub handler { # 1st argument is signal name
587 my($sig) = @_;
588 print "Caught a SIG$sig--shutting down\n";
589 close(LOG);
590 exit(0);
591 }
592
593 $SIG{'INT'} = \&handler;
594 $SIG{'QUIT'} = \&handler;
595 ...
596 $SIG{'INT'} = 'DEFAULT'; # restore default action
597 $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
598
599 Using a value of 'IGNORE' usually has the effect of ignoring
600 the signal, except for the "CHLD" signal. See perlipc for more
601 about this special case. Using an empty string or "undef" as
602 the value has the same effect as 'DEFAULT'.
603
604 Here are some other examples:
605
606 $SIG{"PIPE"} = "Plumber"; # assumes main::Plumber (not
607 # recommended)
608 $SIG{"PIPE"} = \&Plumber; # just fine; assume current
609 # Plumber
610 $SIG{"PIPE"} = *Plumber; # somewhat esoteric
611 $SIG{"PIPE"} = Plumber(); # oops, what did Plumber()
612 # return??
613
614 Be sure not to use a bareword as the name of a signal handler,
615 lest you inadvertently call it.
616
617 Using a string that doesn't correspond to any existing function
618 or a glob that doesn't contain a code slot is equivalent to
619 'IGNORE', but a warning is emitted when the handler is being
620 called (the warning is not emitted for the internal hooks
621 described below).
622
623 If your system has the sigaction() function then signal
624 handlers are installed using it. This means you get reliable
625 signal handling.
626
627 The default delivery policy of signals changed in Perl v5.8.0
628 from immediate (also known as "unsafe") to deferred, also known
629 as "safe signals". See perlipc for more information.
630
631 Certain internal hooks can be also set using the %SIG hash.
632 The routine indicated by $SIG{__WARN__} is called when a
633 warning message is about to be printed. The warning message is
634 passed as the first argument. The presence of a "__WARN__"
635 hook causes the ordinary printing of warnings to "STDERR" to be
636 suppressed. You can use this to save warnings in a variable,
637 or turn warnings into fatal errors, like this:
638
639 local $SIG{__WARN__} = sub { die $_[0] };
640 eval $proggie;
641
642 As the 'IGNORE' hook is not supported by "__WARN__", its effect
643 is the same as using 'DEFAULT'. You can disable warnings using
644 the empty subroutine:
645
646 local $SIG{__WARN__} = sub {};
647
648 The routine indicated by $SIG{__DIE__} is called when a fatal
649 exception is about to be thrown. The error message is passed
650 as the first argument. When a "__DIE__" hook routine returns,
651 the exception processing continues as it would have in the
652 absence of the hook, unless the hook routine itself exits via a
653 "goto &sub", a loop exit, or a die(). The "__DIE__" handler is
654 explicitly disabled during the call, so that you can die from a
655 "__DIE__" handler. Similarly for "__WARN__".
656
657 The $SIG{__DIE__} hook is called even inside an eval(). It was
658 never intended to happen this way, but an implementation glitch
659 made this possible. This used to be deprecated, as it allowed
660 strange action at a distance like rewriting a pending exception
661 in $@. Plans to rectify this have been scrapped, as users found
662 that rewriting a pending exception is actually a useful
663 feature, and not a bug.
664
665 The $SIG{__DIE__} doesn't support 'IGNORE'; it has the same
666 effect as 'DEFAULT'.
667
668 "__DIE__"/"__WARN__" handlers are very special in one respect:
669 they may be called to report (probable) errors found by the
670 parser. In such a case the parser may be in inconsistent
671 state, so any attempt to evaluate Perl code from such a handler
672 will probably result in a segfault. This means that warnings
673 or errors that result from parsing Perl should be used with
674 extreme caution, like this:
675
676 require Carp if defined $^S;
677 Carp::confess("Something wrong") if defined &Carp::confess;
678 die "Something wrong, but could not load Carp to give "
679 . "backtrace...\n\t"
680 . "To see backtrace try starting Perl with -MCarp switch";
681
682 Here the first line will load "Carp" unless it is the parser
683 who called the handler. The second line will print backtrace
684 and die if "Carp" was available. The third line will be
685 executed only if "Carp" was not available.
686
687 Having to even think about the $^S variable in your exception
688 handlers is simply wrong. $SIG{__DIE__} as currently
689 implemented invites grievous and difficult to track down
690 errors. Avoid it and use an "END{}" or CORE::GLOBAL::die
691 override instead.
692
693 See "die" in perlfunc, "warn" in perlfunc, "eval" in perlfunc,
694 and warnings for additional information.
695
696 %{^HOOK}
697 This hash contains coderefs which are called when various perl
698 keywords which are hard or impossible to wrap are called. The
699 keys of this hash are named after the keyword that is being
700 hooked, followed by two underbars and then a phase term; either
701 "before" or "after".
702
703 Perl will throw an error if you attempt modify a key which is
704 not documented to exist, or if you attempt to store anything
705 other than a code reference or undef in the hash. If you wish
706 to use an object to implement a hook you can use currying to
707 embed the object into an anonymous code reference.
708
709 Currently there is only one keyword which can be hooked,
710 "require", but it is expected that in future releases there
711 will be additional keywords with hook support.
712
713 require__before
714 The routine indicated by "${^HOOK}{require__before}" is
715 called by "require" before it checks %INC, looks up @INC,
716 calls INC hooks, or compiles any code. It is called with a
717 single argument, the filename for the item being required
718 (package names are converted to paths). It may alter this
719 filename to change what file is loaded. If the hook dies
720 during execution then it will block the require from
721 executing.
722
723 In order to make it easy to perform an action with shared
724 state both before and after the require keyword was
725 executed the "require__before" hook may return a "post-
726 action" coderef which will in turn be executed when the
727 "require" completes. This coderef will be executed
728 regardless as to whether the require completed succesfully
729 or threw an exception. It will be called with the filename
730 that was required. You can check %INC to determine if the
731 require was successful. Any other return from the
732 "require__before" hook will be silently ignored.
733
734 "require__before" hooks are called in FIFO order, and if
735 the hook returns a code reference those code references
736 will be called in FILO order. In other words if A requires
737 B requires C, then "require__before" will be called first
738 for A, then B and then C, and the post-action code
739 reference will executed first for C, then B and then
740 finally A.
741
742 Well behaved code should ensure that when setting up a
743 "require__before" hook that any prior installed hook will
744 be called, and that their return value, if a code
745 reference, will be called as well. See "require" in
746 perlfunc for an example implementation.
747
748 require__after
749 The routine indicated by "${^HOOK}{require__after}" is
750 called by "require" after the require completes. It is
751 called with a single argument, the filename for the item
752 being required (package names are converted to paths). It
753 is executed when the "require" completes, either via
754 exception or via completion of the require statement, and
755 you can check %INC to determine if the require was
756 successful.
757
758 The "require__after" hook is called for each required file
759 in FILO order. In other words if A requires B requires C,
760 then "require__after" will be called first for C, then B
761 and then A.
762
763 $BASETIME
764 $^T The time at which the program began running, in seconds since
765 the epoch (beginning of 1970). The values returned by the -M,
766 -A, and -C filetests are based on this value.
767
768 $PERL_VERSION
769 $^V The revision, version, and subversion of the Perl interpreter,
770 represented as a version object.
771
772 This variable first appeared in perl v5.6.0; earlier versions
773 of perl will see an undefined value. Before perl v5.10.0 $^V
774 was represented as a v-string rather than a version object.
775
776 $^V can be used to determine whether the Perl interpreter
777 executing a script is in the right range of versions. For
778 example:
779
780 warn "Hashes not randomized!\n" if !$^V or $^V lt v5.8.1
781
782 While version objects overload stringification, to portably
783 convert $^V into its string representation, use sprintf()'s
784 "%vd" conversion, which works for both v-strings or version
785 objects:
786
787 printf "version is v%vd\n", $^V; # Perl's version
788
789 See the documentation of "use VERSION" and "require VERSION"
790 for a convenient way to fail if the running Perl interpreter is
791 too old.
792
793 See also "$]" for a decimal representation of the Perl version.
794
795 The main advantage of $^V over $] is that, for Perl v5.10.0 or
796 later, it overloads operators, allowing easy comparison against
797 other version representations (e.g. decimal, literal v-string,
798 "v1.2.3", or objects). The disadvantage is that prior to
799 v5.10.0, it was only a literal v-string, which can't be easily
800 printed or compared, whereas the behavior of $] is unchanged on
801 all versions of Perl.
802
803 Mnemonic: use ^V for a version object.
804
805 $EXECUTABLE_NAME
806 $^X The name used to execute the current copy of Perl, from C's
807 "argv[0]" or (where supported) /proc/self/exe.
808
809 Depending on the host operating system, the value of $^X may be
810 a relative or absolute pathname of the perl program file, or
811 may be the string used to invoke perl but not the pathname of
812 the perl program file. Also, most operating systems permit
813 invoking programs that are not in the PATH environment
814 variable, so there is no guarantee that the value of $^X is in
815 PATH. For VMS, the value may or may not include a version
816 number.
817
818 You usually can use the value of $^X to re-invoke an
819 independent copy of the same perl that is currently running,
820 e.g.,
821
822 @first_run = `$^X -le "print int rand 100 for 1..100"`;
823
824 But recall that not all operating systems support forking or
825 capturing of the output of commands, so this complex statement
826 may not be portable.
827
828 It is not safe to use the value of $^X as a path name of a
829 file, as some operating systems that have a mandatory suffix on
830 executable files do not require use of the suffix when invoking
831 a command. To convert the value of $^X to a path name, use the
832 following statements:
833
834 # Build up a set of file names (not command names).
835 use Config;
836 my $this_perl = $^X;
837 if ($^O ne 'VMS') {
838 $this_perl .= $Config{_exe}
839 unless $this_perl =~ m/$Config{_exe}$/i;
840 }
841
842 Because many operating systems permit anyone with read access
843 to the Perl program file to make a copy of it, patch the copy,
844 and then execute the copy, the security-conscious Perl
845 programmer should take care to invoke the installed copy of
846 perl, not the copy referenced by $^X. The following statements
847 accomplish this goal, and produce a pathname that can be
848 invoked as a command or referenced as a file.
849
850 use Config;
851 my $secure_perl_path = $Config{perlpath};
852 if ($^O ne 'VMS') {
853 $secure_perl_path .= $Config{_exe}
854 unless $secure_perl_path =~ m/$Config{_exe}$/i;
855 }
856
857 Variables related to regular expressions
858 Most of the special variables related to regular expressions are side
859 effects. Perl sets these variables when it has completed a match
860 successfully, so you should check the match result before using them.
861 For instance:
862
863 if( /P(A)TT(ER)N/ ) {
864 print "I found $1 and $2\n";
865 }
866
867 These variables are read-only and behave similarly to a dynamically
868 scoped variable, with only a few exceptions which are explicitly
869 documented as behaving otherwise. See the following section for more
870 details.
871
872 Scoping Rules of Regex Variables
873
874 Regular expression variables allow the programmer to access the state
875 of the most recent successful regex match in the current dynamic scope.
876
877 The variables themselves are global and unscoped, but the data they
878 access is scoped similarly to dynamically scoped variables, in that
879 every successful match behaves as though it localizes a global state
880 object to the current block or file scope. (See "Compound Statements"
881 in perlsyn for more details on dynamic scoping and the "local"
882 keyword.)
883
884 A successful match includes any successful match performed by the
885 search and replace operator "s///" as well as those performed by the
886 "m//" operator.
887
888 Consider the following code:
889
890 my @state;
891 sub matchit {
892 push @state, $1; # pushes "baz"
893 my $str = shift;
894 $str =~ /(zat)/; # matches "zat"
895 push @state, $1; # pushes "zat"
896 }
897
898 {
899 $str = "foo bar baz blorp zat";
900 $str =~ /(foo)/; # matches "foo"
901 push @state, $1; # pushes "foo"
902 {
903 $str =~ /(pizza)/; # does NOT match
904 push @state, $1; # pushes "foo"
905 $str =~ /(bar)/; # matches "bar"
906 push @state, $1; # pushes "bar"
907 $str =~ /(baz)/; # matches "baz"
908 matchit($str); # see above
909 push @state, $1; # pushes "baz"
910 }
911 $str =~ s/noodles/rice/; # does NOT match
912 push @state, $1; # pushes "foo"
913 $str =~ s/(blorp)/zwoop/; # matches "blorp"
914 push @state, $1; # pushes "blorp"
915 }
916 # the following prints "foo, foo, bar, baz, zat, baz, foo, blorp"
917 print join ",", @state;
918
919 Notice that each successful match in the exact same scope overrides the
920 match context of the previous successful match, but that unsuccessful
921 matches do not. Also note that in an inner nested scope the previous
922 state from an outer dynamic scope persists until it has been overriden
923 by another successful match, but that when the inner nested scope exits
924 whatever match context was in effect before the inner successful match
925 is restored when the scope concludes.
926
927 It is a known issue that "goto LABEL" may interact poorly with the
928 dynamically scoped match context. This may not be fixable, and is
929 considered to be one of many good reasons to avoid "goto LABEL".
930
931 Performance issues
932
933 Traditionally in Perl, any use of any of the three variables "$`", $&
934 or "$'" (or their "use English" equivalents) anywhere in the code,
935 caused all subsequent successful pattern matches to make a copy of the
936 matched string, in case the code might subsequently access one of those
937 variables. This imposed a considerable performance penalty across the
938 whole program, so generally the use of these variables has been
939 discouraged.
940
941 In Perl 5.6.0 the "@-" and "@+" dynamic arrays were introduced that
942 supply the indices of successful matches. So you could for example do
943 this:
944
945 $str =~ /pattern/;
946
947 print $`, $&, $'; # bad: performance hit
948
949 print # good: no performance hit
950 substr($str, 0, $-[0]),
951 substr($str, $-[0], $+[0]-$-[0]),
952 substr($str, $+[0]);
953
954 In Perl 5.10.0 the "/p" match operator flag and the "${^PREMATCH}",
955 "${^MATCH}", and "${^POSTMATCH}" variables were introduced, that
956 allowed you to suffer the penalties only on patterns marked with "/p".
957
958 In Perl 5.18.0 onwards, perl started noting the presence of each of the
959 three variables separately, and only copied that part of the string
960 required; so in
961
962 $`; $&; "abcdefgh" =~ /d/
963
964 perl would only copy the "abcd" part of the string. That could make a
965 big difference in something like
966
967 $str = 'x' x 1_000_000;
968 $&; # whoops
969 $str =~ /x/g # one char copied a million times, not a million chars
970
971 In Perl 5.20.0 a new copy-on-write system was enabled by default, which
972 finally fixes most of the performance issues with these three
973 variables, and makes them safe to use anywhere.
974
975 The "Devel::NYTProf" and "Devel::FindAmpersand" modules can help you
976 find uses of these problematic match variables in your code.
977
978 $<digits> ($1, $2, ...)
979 Contains the subpattern from the corresponding set of capturing
980 parentheses from the last successful pattern match in the
981 current dynamic scope. (See "Scoping Rules of Regex
982 Variables".)
983
984 Note there is a distinction between a capture buffer which
985 matches the empty string a capture buffer which is optional.
986 Eg, "(x?)" and "(x)?" The latter may be undef, the former not.
987
988 These variables are read-only.
989
990 Mnemonic: like \digits.
991
992 @{^CAPTURE}
993 An array which exposes the contents of the capture buffers, if
994 any, of the last successful pattern match, not counting
995 patterns matched in nested blocks that have been exited
996 already.
997
998 Note that the 0 index of @{^CAPTURE} is equivalent to $1, the 1
999 index is equivalent to $2, etc.
1000
1001 if ("foal"=~/(.)(.)(.)(.)/) {
1002 print join "-", @{^CAPTURE};
1003 }
1004
1005 should output "f-o-a-l".
1006
1007 See also "$<digits> ($1, $2, ...)", "%{^CAPTURE}" and
1008 "%{^CAPTURE_ALL}".
1009
1010 Note that unlike most other regex magic variables there is no
1011 single letter equivalent to "@{^CAPTURE}". Also be aware that
1012 when interpolating subscripts of this array you must use the
1013 demarcated variable form, for instance
1014
1015 print "${^CAPTURE[0]}"
1016
1017 see "Demarcated variable names using braces" in perldata for
1018 more information on this form and its uses.
1019
1020 This variable was added in 5.25.7
1021
1022 $MATCH
1023 $& The string matched by the last successful pattern match. (See
1024 "Scoping Rules of Regex Variables".)
1025
1026 See "Performance issues" above for the serious performance
1027 implications of using this variable (even once) in your code.
1028
1029 This variable is read-only, and its value is dynamically
1030 scoped.
1031
1032 Mnemonic: like "&" in some editors.
1033
1034 ${^MATCH}
1035 It is only guaranteed to return a defined value when the
1036 pattern was compiled or executed with the "/p" modifier.
1037
1038 This is similar to $& ($MATCH) except that to use it you must
1039 use the "/p" modifier when executing the pattern, and it does
1040 not incur and performance penalty associated with that
1041 variable.
1042
1043 See "Performance issues" above.
1044
1045 This variable was added in Perl v5.10.0.
1046
1047 This variable is read-only, and its value is dynamically
1048 scoped.
1049
1050 $PREMATCH
1051 $` The string preceding whatever was matched by the last
1052 successful pattern match. (See "Scoping Rules of Regex
1053 Variables").
1054
1055 See "Performance issues" above for the serious performance
1056 implications of using this variable (even once) in your code.
1057
1058 This variable is read-only, and its value is dynamically
1059 scoped.
1060
1061 Mnemonic: "`" often precedes a quoted string.
1062
1063 ${^PREMATCH}
1064 It is only guaranteed to return a defined value when the
1065 pattern was executed with the "/p" modifier.
1066
1067 This is similar to "$`" ($PREMATCH) except that to use it you
1068 must use the "/p" modifier when executing the pattern, and it
1069 does not incur and performance penalty associated with that
1070 variable.
1071
1072 See "Performance issues" above.
1073
1074 This variable was added in Perl v5.10.0.
1075
1076 This variable is read-only, and its value is dynamically
1077 scoped.
1078
1079 $POSTMATCH
1080 $' The string following whatever was matched by the last
1081 successful pattern match. (See "Scoping Rules of Regex
1082 Variables"). Example:
1083
1084 local $_ = 'abcdefghi';
1085 /def/;
1086 print "$`:$&:$'\n"; # prints abc:def:ghi
1087
1088 See "Performance issues" above for the serious performance
1089 implications of using this variable (even once) in your code.
1090
1091 This variable is read-only, and its value is dynamically
1092 scoped.
1093
1094 Mnemonic: "'" often follows a quoted string.
1095
1096 ${^POSTMATCH}
1097 It is only guaranteed to return a defined value when the
1098 pattern was compiled or executed with the "/p" modifier.
1099
1100 This is similar to "$'" ($POSTMATCH) except that to use it you
1101 must use the "/p" modifier when executing the pattern, and it
1102 does not incur and performance penalty associated with that
1103 variable.
1104
1105 See "Performance issues" above.
1106
1107 This variable was added in Perl v5.10.0.
1108
1109 This variable is read-only, and its value is dynamically
1110 scoped.
1111
1112 $LAST_PAREN_MATCH
1113 $+ The text matched by the highest used capture group of the last
1114 successful search pattern. (See "Scoping Rules of Regex
1115 Variables"). It is logically equivalent to the highest
1116 numbered capture variable ($1, $2, ...) which has a defined
1117 value.
1118
1119 This is useful if you don't know which one of a set of
1120 alternative patterns matched. For example:
1121
1122 /Version: (.*)|Revision: (.*)/ && ($rev = $+);
1123
1124 This variable is read-only, and its value is dynamically
1125 scoped.
1126
1127 Mnemonic: be positive and forward looking.
1128
1129 $LAST_SUBMATCH_RESULT
1130 $^N The text matched by the used group most-recently closed (i.e.
1131 the group with the rightmost closing parenthesis) of the last
1132 successful match. (See "Scoping Rules of Regex Variables").
1133
1134 This is subtly different from $+. For example in
1135
1136 "ab" =~ /^((.)(.))$/
1137
1138 we have
1139
1140 $1,$^N have the value "ab"
1141 $2 has the value "a"
1142 $3,$+ have the value "b"
1143
1144 This is primarily used inside "(?{...})" blocks for examining
1145 text recently matched. For example, to effectively capture
1146 text to a variable (in addition to $1, $2, etc.), replace
1147 "(...)" with
1148
1149 (?:(...)(?{ $var = $^N }))
1150
1151 By setting and then using $var in this way relieves you from
1152 having to worry about exactly which numbered set of parentheses
1153 they are.
1154
1155 This variable is read-only, and its value is dynamically
1156 scoped.
1157
1158 This variable was added in Perl v5.8.0.
1159
1160 Mnemonic: the (possibly) Nested parenthesis that most recently
1161 closed.
1162
1163 @LAST_MATCH_END
1164 @+ This array holds the offsets of the ends of the last successful
1165 match and any matching capture buffers that the pattern
1166 contains. (See "Scoping Rules of Regex Variables")
1167
1168 The number of elements it contains will be one more than the
1169 number of capture buffers in the pattern, regardless of which
1170 capture buffers actually matched. You can use this to determine
1171 how many capture buffers there are in the pattern. (As opposed
1172 to "@-" which may have fewer elements.)
1173
1174 $+[0] is the offset into the string of the end of the entire
1175 match. This is the same value as what the "pos" function
1176 returns when called on the variable that was matched against.
1177 The nth element of this array holds the offset of the nth
1178 submatch, so $+[1] is the offset past where $1 ends, $+[2] the
1179 offset past where $2 ends, and so on. You can use $#+ to
1180 determine how many subgroups were in the last successful match.
1181 See the examples given for the "@-" variable.
1182
1183 This variable is read-only, and its value is dynamically
1184 scoped.
1185
1186 This variable was added in Perl v5.6.0.
1187
1188 %{^CAPTURE}
1189 %LAST_PAREN_MATCH
1190 %+ Similar to "@+", the "%+" hash allows access to the named
1191 capture buffers, should they exist, in the last successful
1192 match in the currently active dynamic scope. (See "Scoping
1193 Rules of Regex Variables").
1194
1195 For example, $+{foo} is equivalent to $1 after the following
1196 match:
1197
1198 'foo' =~ /(?<foo>foo)/;
1199
1200 The keys of the "%+" hash list only the names of buffers that
1201 have captured (and that are thus associated to defined values).
1202
1203 If multiple distinct capture groups have the same name, then
1204 $+{NAME} will refer to the leftmost defined group in the match.
1205
1206 The underlying behaviour of "%+" is provided by the
1207 Tie::Hash::NamedCapture module.
1208
1209 Note: "%-" and "%+" are tied views into a common internal hash
1210 associated with the last successful regular expression.
1211 Therefore mixing iterative access to them via "each" may have
1212 unpredictable results. Likewise, if the last successful match
1213 changes, then the results may be surprising.
1214
1215 This variable was added in Perl v5.10.0. The "%{^CAPTURE}"
1216 alias was added in 5.25.7.
1217
1218 This variable is read-only, and its value is dynamically
1219 scoped.
1220
1221 @LAST_MATCH_START
1222 @- This array holds the offsets of the beginnings of the last
1223 successful match and any capture buffers it contains. (See
1224 "Scoping Rules of Regex Variables").
1225
1226 The number of elements it contains will be one more than the
1227 number of the highest capture buffers (also called a subgroup)
1228 that actually matched something. (As opposed to "@+" which may
1229 have fewer elements.)
1230
1231 "$-[0]" is the offset of the start of the last successful
1232 match. "$-[n]" is the offset of the start of the substring
1233 matched by n-th subpattern, or undef if the subpattern did not
1234 match.
1235
1236 Thus, after a match against $_, $& coincides with "substr $_,
1237 $-[0], $+[0] - $-[0]". Similarly, "$n" coincides with "substr
1238 $_, $-[n], $+[n] - $-[n]" if "$-[n]" is defined, and $+
1239 coincides with "substr $_, $-[$#-], $+[$#-] - $-[$#-]". One
1240 can use "$#-" to find the last matched subgroup in the last
1241 successful match. Contrast with $#+, the number of subgroups
1242 in the regular expression.
1243
1244 "$-[0]" is the offset into the string of the beginning of the
1245 entire match. The nth element of this array holds the offset
1246 of the nth submatch, so "$-[1]" is the offset where $1 begins,
1247 "$-[2]" the offset where $2 begins, and so on.
1248
1249 After a match against some variable $var:
1250
1251 "$`" is the same as "substr($var, 0, $-[0])"
1252 $& is the same as "substr($var, $-[0], $+[0] - $-[0])"
1253 "$'" is the same as "substr($var, $+[0])"
1254 $1 is the same as "substr($var, $-[1], $+[1] - $-[1])"
1255 $2 is the same as "substr($var, $-[2], $+[2] - $-[2])"
1256 $3 is the same as "substr($var, $-[3], $+[3] - $-[3])"
1257
1258 This variable is read-only, and its value is dynamically
1259 scoped.
1260
1261 This variable was added in Perl v5.6.0.
1262
1263 %{^CAPTURE_ALL}
1264 %- Similar to "%+", this variable allows access to the named
1265 capture groups in the last successful match in the currently
1266 active dynamic scope. (See "Scoping Rules of Regex Variables").
1267 To each capture group name found in the regular expression, it
1268 associates a reference to an array containing the list of
1269 values captured by all buffers with that name (should there be
1270 several of them), in the order where they appear.
1271
1272 Here's an example:
1273
1274 if ('1234' =~ /(?<A>1)(?<B>2)(?<A>3)(?<B>4)/) {
1275 foreach my $bufname (sort keys %-) {
1276 my $ary = $-{$bufname};
1277 foreach my $idx (0..$#$ary) {
1278 print "\$-{$bufname}[$idx] : ",
1279 (defined($ary->[$idx])
1280 ? "'$ary->[$idx]'"
1281 : "undef"),
1282 "\n";
1283 }
1284 }
1285 }
1286
1287 would print out:
1288
1289 $-{A}[0] : '1'
1290 $-{A}[1] : '3'
1291 $-{B}[0] : '2'
1292 $-{B}[1] : '4'
1293
1294 The keys of the "%-" hash correspond to all buffer names found
1295 in the regular expression.
1296
1297 The behaviour of "%-" is implemented via the
1298 Tie::Hash::NamedCapture module.
1299
1300 Note: "%-" and "%+" are tied views into a common internal hash
1301 associated with the last successful regular expression.
1302 Therefore mixing iterative access to them via "each" may have
1303 unpredictable results. Likewise, if the last successful match
1304 changes, then the results may be surprising. See "Scoping Rules
1305 of Regex Variables".
1306
1307 This variable was added in Perl v5.10.0. The "%{^CAPTURE_ALL}"
1308 alias was added in 5.25.7.
1309
1310 This variable is read-only, and its value is dynamically
1311 scoped.
1312
1313 ${^LAST_SUCCESSFUL_PATTERN}
1314 The last successful pattern that matched in the current scope.
1315 The empty pattern defaults to matching to this. For instance:
1316
1317 if (m/foo/ || m/bar/) {
1318 s//BLAH/;
1319 }
1320
1321 and
1322
1323 if (m/foo/ || m/bar/) {
1324 s/${^LAST_SUCCESSFUL_PATTERN}/BLAH/;
1325 }
1326
1327 are equivalent.
1328
1329 You can use this to debug which pattern matched last, or to
1330 match with it again.
1331
1332 Added in Perl 5.37.10.
1333
1334 $LAST_REGEXP_CODE_RESULT
1335 $^R The result of evaluation of the last successful "(?{ code })"
1336 regular expression assertion (see perlre).
1337
1338 This variable may be written to, and its value is scoped
1339 normally, unlike most other regex variables.
1340
1341 This variable was added in Perl 5.005.
1342
1343 ${^RE_COMPILE_RECURSION_LIMIT}
1344 The current value giving the maximum number of open but
1345 unclosed parenthetical groups there may be at any point during
1346 a regular expression compilation. The default is currently
1347 1000 nested groups. You may adjust it depending on your needs
1348 and the amount of memory available.
1349
1350 This variable was added in Perl v5.30.0.
1351
1352 ${^RE_DEBUG_FLAGS}
1353 The current value of the regex debugging flags. Set to 0 for
1354 no debug output even when the "re 'debug'" module is loaded.
1355 See re for details.
1356
1357 This variable was added in Perl v5.10.0.
1358
1359 ${^RE_TRIE_MAXBUF}
1360 Controls how certain regex optimisations are applied and how
1361 much memory they utilize. This value by default is 65536 which
1362 corresponds to a 512kB temporary cache. Set this to a higher
1363 value to trade memory for speed when matching large
1364 alternations. Set it to a lower value if you want the
1365 optimisations to be as conservative of memory as possible but
1366 still occur, and set it to a negative value to prevent the
1367 optimisation and conserve the most memory. Under normal
1368 situations this variable should be of no interest to you.
1369
1370 This variable was added in Perl v5.10.0.
1371
1372 Variables related to filehandles
1373 Variables that depend on the currently selected filehandle may be set
1374 by calling an appropriate object method on the "IO::Handle" object,
1375 although this is less efficient than using the regular built-in
1376 variables. (Summary lines below for this contain the word HANDLE.)
1377 First you must say
1378
1379 use IO::Handle;
1380
1381 after which you may use either
1382
1383 method HANDLE EXPR
1384
1385 or more safely,
1386
1387 HANDLE->method(EXPR)
1388
1389 Each method returns the old value of the "IO::Handle" attribute. The
1390 methods each take an optional EXPR, which, if supplied, specifies the
1391 new value for the "IO::Handle" attribute in question. If not supplied,
1392 most methods do nothing to the current value--except for autoflush(),
1393 which will assume a 1 for you, just to be different.
1394
1395 Because loading in the "IO::Handle" class is an expensive operation,
1396 you should learn how to use the regular built-in variables.
1397
1398 A few of these variables are considered "read-only". This means that
1399 if you try to assign to this variable, either directly or indirectly
1400 through a reference, you'll raise a run-time exception.
1401
1402 You should be very careful when modifying the default values of most
1403 special variables described in this document. In most cases you want
1404 to localize these variables before changing them, since if you don't,
1405 the change may affect other modules which rely on the default values of
1406 the special variables that you have changed. This is one of the
1407 correct ways to read the whole file at once:
1408
1409 open my $fh, "<", "foo" or die $!;
1410 local $/; # enable localized slurp mode
1411 my $content = <$fh>;
1412 close $fh;
1413
1414 But the following code is quite bad:
1415
1416 open my $fh, "<", "foo" or die $!;
1417 undef $/; # enable slurp mode
1418 my $content = <$fh>;
1419 close $fh;
1420
1421 since some other module, may want to read data from some file in the
1422 default "line mode", so if the code we have just presented has been
1423 executed, the global value of $/ is now changed for any other code
1424 running inside the same Perl interpreter.
1425
1426 Usually when a variable is localized you want to make sure that this
1427 change affects the shortest scope possible. So unless you are already
1428 inside some short "{}" block, you should create one yourself. For
1429 example:
1430
1431 my $content = '';
1432 open my $fh, "<", "foo" or die $!;
1433 {
1434 local $/;
1435 $content = <$fh>;
1436 }
1437 close $fh;
1438
1439 Here is an example of how your own code can go broken:
1440
1441 for ( 1..3 ){
1442 $\ = "\r\n";
1443 nasty_break();
1444 print "$_";
1445 }
1446
1447 sub nasty_break {
1448 $\ = "\f";
1449 # do something with $_
1450 }
1451
1452 You probably expect this code to print the equivalent of
1453
1454 "1\r\n2\r\n3\r\n"
1455
1456 but instead you get:
1457
1458 "1\f2\f3\f"
1459
1460 Why? Because nasty_break() modifies "$\" without localizing it first.
1461 The value you set in nasty_break() is still there when you return.
1462 The fix is to add local() so the value doesn't leak out of
1463 nasty_break():
1464
1465 local $\ = "\f";
1466
1467 It's easy to notice the problem in such a short example, but in more
1468 complicated code you are looking for trouble if you don't localize
1469 changes to the special variables.
1470
1471 $ARGV Contains the name of the current file when reading from "<>".
1472
1473 @ARGV The array @ARGV contains the command-line arguments intended
1474 for the script. $#ARGV is generally the number of arguments
1475 minus one, because $ARGV[0] is the first argument, not the
1476 program's command name itself. See "$0" for the command name.
1477
1478 ARGV The special filehandle that iterates over command-line
1479 filenames in @ARGV. Usually written as the null filehandle in
1480 the angle operator "<>". Note that currently "ARGV" only has
1481 its magical effect within the "<>" operator; elsewhere it is
1482 just a plain filehandle corresponding to the last file opened
1483 by "<>". In particular, passing "\*ARGV" as a parameter to a
1484 function that expects a filehandle may not cause your function
1485 to automatically read the contents of all the files in @ARGV.
1486
1487 ARGVOUT The special filehandle that points to the currently open output
1488 file when doing edit-in-place processing with -i. Useful when
1489 you have to do a lot of inserting and don't want to keep
1490 modifying $_. See perlrun for the -i switch.
1491
1492 IO::Handle->output_field_separator( EXPR )
1493 $OUTPUT_FIELD_SEPARATOR
1494 $OFS
1495 $, The output field separator for the print operator. If defined,
1496 this value is printed between each of print's arguments.
1497 Default is "undef".
1498
1499 You cannot call output_field_separator() on a handle, only as a
1500 static method. See IO::Handle.
1501
1502 Mnemonic: what is printed when there is a "," in your print
1503 statement.
1504
1505 HANDLE->input_line_number( EXPR )
1506 $INPUT_LINE_NUMBER
1507 $NR
1508 $. Current line number for the last filehandle accessed.
1509
1510 Each filehandle in Perl counts the number of lines that have
1511 been read from it. (Depending on the value of $/, Perl's idea
1512 of what constitutes a line may not match yours.) When a line
1513 is read from a filehandle (via readline() or "<>"), or when
1514 tell() or seek() is called on it, $. becomes an alias to the
1515 line counter for that filehandle.
1516
1517 You can adjust the counter by assigning to $., but this will
1518 not actually move the seek pointer. Localizing $. will not
1519 localize the filehandle's line count. Instead, it will
1520 localize perl's notion of which filehandle $. is currently
1521 aliased to.
1522
1523 $. is reset when the filehandle is closed, but not when an open
1524 filehandle is reopened without an intervening close(). For
1525 more details, see "I/O Operators" in perlop. Because "<>"
1526 never does an explicit close, line numbers increase across
1527 "ARGV" files (but see examples in "eof" in perlfunc).
1528
1529 You can also use "HANDLE->input_line_number(EXPR)" to access
1530 the line counter for a given filehandle without having to worry
1531 about which handle you last accessed.
1532
1533 Mnemonic: many programs use "." to mean the current line
1534 number.
1535
1536 IO::Handle->input_record_separator( EXPR )
1537 $INPUT_RECORD_SEPARATOR
1538 $RS
1539 $/ The input record separator, newline by default. This
1540 influences Perl's idea of what a "line" is. Works like awk's
1541 RS variable, including treating empty lines as a terminator if
1542 set to the null string (an empty line cannot contain any spaces
1543 or tabs). You may set it to a multi-character string to match
1544 a multi-character terminator, or to "undef" to read through the
1545 end of file. Setting it to "\n\n" means something slightly
1546 different than setting to "", if the file contains consecutive
1547 empty lines. Setting to "" will treat two or more consecutive
1548 empty lines as a single empty line. Setting to "\n\n" will
1549 blindly assume that the next input character belongs to the
1550 next paragraph, even if it's a newline.
1551
1552 local $/; # enable "slurp" mode
1553 local $_ = <FH>; # whole file now here
1554 s/\n[ \t]+/ /g;
1555
1556 Remember: the value of $/ is a string, not a regex. awk has to
1557 be better for something. :-)
1558
1559 Setting $/ to an empty string -- the so-called paragraph mode
1560 -- merits special attention. When $/ is set to "" and the
1561 entire file is read in with that setting, any sequence of one
1562 or more consecutive newlines at the beginning of the file is
1563 discarded. With the exception of the final record in the file,
1564 each sequence of characters ending in two or more newlines is
1565 treated as one record and is read in to end in exactly two
1566 newlines. If the last record in the file ends in zero or one
1567 consecutive newlines, that record is read in with that number
1568 of newlines. If the last record ends in two or more
1569 consecutive newlines, it is read in with two newlines like all
1570 preceding records.
1571
1572 Suppose we wrote the following string to a file:
1573
1574 my $string = "\n\n\n";
1575 $string .= "alpha beta\ngamma delta\n\n\n";
1576 $string .= "epsilon zeta eta\n\n";
1577 $string .= "theta\n";
1578
1579 my $file = 'simple_file.txt';
1580 open my $OUT, '>', $file or die;
1581 print $OUT $string;
1582 close $OUT or die;
1583
1584 Now we read that file in paragraph mode:
1585
1586 local $/ = ""; # paragraph mode
1587 open my $IN, '<', $file or die;
1588 my @records = <$IN>;
1589 close $IN or die;
1590
1591 @records will consist of these 3 strings:
1592
1593 (
1594 "alpha beta\ngamma delta\n\n",
1595 "epsilon zeta eta\n\n",
1596 "theta\n",
1597 )
1598
1599 Setting $/ to a reference to an integer, scalar containing an
1600 integer, or scalar that's convertible to an integer will
1601 attempt to read records instead of lines, with the maximum
1602 record size being the referenced integer number of characters.
1603 So this:
1604
1605 local $/ = \32768; # or \"32768", or \$var_containing_32768
1606 open my $fh, "<", $myfile or die $!;
1607 local $_ = <$fh>;
1608
1609 will read a record of no more than 32768 characters from $fh.
1610 If you're not reading from a record-oriented file (or your OS
1611 doesn't have record-oriented files), then you'll likely get a
1612 full chunk of data with every read. If a record is larger than
1613 the record size you've set, you'll get the record back in
1614 pieces. Trying to set the record size to zero or less is
1615 deprecated and will cause $/ to have the value of "undef",
1616 which will cause reading in the (rest of the) whole file.
1617
1618 As of 5.19.9 setting $/ to any other form of reference will
1619 throw a fatal exception. This is in preparation for supporting
1620 new ways to set $/ in the future.
1621
1622 On VMS only, record reads bypass PerlIO layers and any
1623 associated buffering, so you must not mix record and non-record
1624 reads on the same filehandle. Record mode mixes with line mode
1625 only when the same buffering layer is in use for both modes.
1626
1627 You cannot call input_record_separator() on a handle, only as a
1628 static method. See IO::Handle.
1629
1630 See also "Newlines" in perlport. Also see "$.".
1631
1632 Mnemonic: / delimits line boundaries when quoting poetry.
1633
1634 IO::Handle->output_record_separator( EXPR )
1635 $OUTPUT_RECORD_SEPARATOR
1636 $ORS
1637 $\ The output record separator for the print operator. If
1638 defined, this value is printed after the last of print's
1639 arguments. Default is "undef".
1640
1641 You cannot call output_record_separator() on a handle, only as
1642 a static method. See IO::Handle.
1643
1644 Mnemonic: you set "$\" instead of adding "\n" at the end of the
1645 print. Also, it's just like $/, but it's what you get "back"
1646 from Perl.
1647
1648 HANDLE->autoflush( EXPR )
1649 $OUTPUT_AUTOFLUSH
1650 $| If set to nonzero, forces a flush right away and after every
1651 write or print on the currently selected output channel.
1652 Default is 0 (regardless of whether the channel is really
1653 buffered by the system or not; $| tells you only whether you've
1654 asked Perl explicitly to flush after each write). STDOUT will
1655 typically be line buffered if output is to the terminal and
1656 block buffered otherwise. Setting this variable is useful
1657 primarily when you are outputting to a pipe or socket, such as
1658 when you are running a Perl program under rsh and want to see
1659 the output as it's happening. This has no effect on input
1660 buffering. See "getc" in perlfunc for that. See "select" in
1661 perlfunc on how to select the output channel. See also
1662 IO::Handle.
1663
1664 Mnemonic: when you want your pipes to be piping hot.
1665
1666 ${^LAST_FH}
1667 This read-only variable contains a reference to the last-read
1668 filehandle. This is set by "<HANDLE>", "readline", "tell",
1669 "eof" and "seek". This is the same handle that $. and "tell"
1670 and "eof" without arguments use. It is also the handle used
1671 when Perl appends ", <STDIN> line 1" to an error or warning
1672 message.
1673
1674 This variable was added in Perl v5.18.0.
1675
1676 Variables related to formats
1677
1678 The special variables for formats are a subset of those for
1679 filehandles. See perlform for more information about Perl's formats.
1680
1681 $ACCUMULATOR
1682 $^A The current value of the write() accumulator for format()
1683 lines. A format contains formline() calls that put their
1684 result into $^A. After calling its format, write() prints out
1685 the contents of $^A and empties. So you never really see the
1686 contents of $^A unless you call formline() yourself and then
1687 look at it. See perlform and "formline PICTURE,LIST" in
1688 perlfunc.
1689
1690 IO::Handle->format_formfeed(EXPR)
1691 $FORMAT_FORMFEED
1692 $^L What formats output as a form feed. The default is "\f".
1693
1694 You cannot call format_formfeed() on a handle, only as a static
1695 method. See IO::Handle.
1696
1697 HANDLE->format_page_number(EXPR)
1698 $FORMAT_PAGE_NUMBER
1699 $% The current page number of the currently selected output
1700 channel.
1701
1702 Mnemonic: "%" is page number in nroff.
1703
1704 HANDLE->format_lines_left(EXPR)
1705 $FORMAT_LINES_LEFT
1706 $- The number of lines left on the page of the currently selected
1707 output channel.
1708
1709 Mnemonic: lines_on_page - lines_printed.
1710
1711 IO::Handle->format_line_break_characters EXPR
1712 $FORMAT_LINE_BREAK_CHARACTERS
1713 $: The current set of characters after which a string may be
1714 broken to fill continuation fields (starting with "^") in a
1715 format. The default is " \n-", to break on a space, newline,
1716 or a hyphen.
1717
1718 You cannot call format_line_break_characters() on a handle,
1719 only as a static method. See IO::Handle.
1720
1721 Mnemonic: a "colon" in poetry is a part of a line.
1722
1723 HANDLE->format_lines_per_page(EXPR)
1724 $FORMAT_LINES_PER_PAGE
1725 $= The current page length (printable lines) of the currently
1726 selected output channel. The default is 60.
1727
1728 Mnemonic: = has horizontal lines.
1729
1730 HANDLE->format_top_name(EXPR)
1731 $FORMAT_TOP_NAME
1732 $^ The name of the current top-of-page format for the currently
1733 selected output channel. The default is the name of the
1734 filehandle with "_TOP" appended. For example, the default
1735 format top name for the "STDOUT" filehandle is "STDOUT_TOP".
1736
1737 Mnemonic: points to top of page.
1738
1739 HANDLE->format_name(EXPR)
1740 $FORMAT_NAME
1741 $~ The name of the current report format for the currently
1742 selected output channel. The default format name is the same
1743 as the filehandle name. For example, the default format name
1744 for the "STDOUT" filehandle is just "STDOUT".
1745
1746 Mnemonic: brother to $^.
1747
1748 Error Variables
1749 The variables $@, $!, $^E, and $? contain information about different
1750 types of error conditions that may appear during execution of a Perl
1751 program. The variables are shown ordered by the "distance" between the
1752 subsystem which reported the error and the Perl process. They
1753 correspond to errors detected by the Perl interpreter, C library,
1754 operating system, or an external program, respectively.
1755
1756 To illustrate the differences between these variables, consider the
1757 following Perl expression, which uses a single-quoted string. After
1758 execution of this statement, perl may have set all four special error
1759 variables:
1760
1761 eval q{
1762 open my $pipe, "/cdrom/install |" or die $!;
1763 my @res = <$pipe>;
1764 close $pipe or die "bad pipe: $?, $!";
1765 };
1766
1767 When perl executes the eval() expression, it translates the open(),
1768 "<PIPE>", and "close" calls in the C run-time library and thence to the
1769 operating system kernel. perl sets $! to the C library's "errno" if
1770 one of these calls fails.
1771
1772 $@ is set if the string to be "eval"-ed did not compile (this may
1773 happen if "open" or "close" were imported with bad prototypes), or if
1774 Perl code executed during evaluation die()d. In these cases the value
1775 of $@ is the compile error, or the argument to "die" (which will
1776 interpolate $! and $?). (See also Fatal, though.)
1777
1778 Under a few operating systems, $^E may contain a more verbose error
1779 indicator, such as in this case, "CDROM tray not closed." Systems that
1780 do not support extended error messages leave $^E the same as $!.
1781
1782 Finally, $? may be set to a non-0 value if the external program
1783 /cdrom/install fails. The upper eight bits reflect specific error
1784 conditions encountered by the program (the program's exit() value).
1785 The lower eight bits reflect mode of failure, like signal death and
1786 core dump information. See wait(2) for details. In contrast to $! and
1787 $^E, which are set only if an error condition is detected, the variable
1788 $? is set on each "wait" or pipe "close", overwriting the old value.
1789 This is more like $@, which on every eval() is always set on failure
1790 and cleared on success.
1791
1792 For more details, see the individual descriptions at $@, $!, $^E, and
1793 $?.
1794
1795 ${^CHILD_ERROR_NATIVE}
1796 The native status returned by the last pipe close, backtick
1797 (``) command, successful call to wait() or waitpid(), or from
1798 the system() operator. On POSIX-like systems this value can be
1799 decoded with the WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG,
1800 WIFSTOPPED, and WSTOPSIG functions provided by the POSIX
1801 module.
1802
1803 Under VMS this reflects the actual VMS exit status; i.e. it is
1804 the same as $? when the pragma "use vmsish 'status'" is in
1805 effect.
1806
1807 This variable was added in Perl v5.10.0.
1808
1809 $EXTENDED_OS_ERROR
1810 $^E Error information specific to the current operating system. At
1811 the moment, this differs from "$!" under only VMS, OS/2, and
1812 Win32 (and for MacPerl). On all other platforms, $^E is always
1813 just the same as $!.
1814
1815 Under VMS, $^E provides the VMS status value from the last
1816 system error. This is more specific information about the last
1817 system error than that provided by $!. This is particularly
1818 important when $! is set to EVMSERR.
1819
1820 Under OS/2, $^E is set to the error code of the last call to
1821 OS/2 API either via CRT, or directly from perl.
1822
1823 Under Win32, $^E always returns the last error information
1824 reported by the Win32 call GetLastError() which describes the
1825 last error from within the Win32 API. Most Win32-specific code
1826 will report errors via $^E. ANSI C and Unix-like calls set
1827 "errno" and so most portable Perl code will report errors via
1828 $!.
1829
1830 Caveats mentioned in the description of "$!" generally apply to
1831 $^E, also.
1832
1833 This variable was added in Perl 5.003.
1834
1835 Mnemonic: Extra error explanation.
1836
1837 $EXCEPTIONS_BEING_CAUGHT
1838 $^S Current state of the interpreter.
1839
1840 $^S State
1841 --------- -------------------------------------
1842 undef Parsing module, eval, or main program
1843 true (1) Executing an eval or try block
1844 false (0) Otherwise
1845
1846 The first state may happen in $SIG{__DIE__} and $SIG{__WARN__}
1847 handlers.
1848
1849 The English name $EXCEPTIONS_BEING_CAUGHT is slightly
1850 misleading, because the "undef" value does not indicate whether
1851 exceptions are being caught, since compilation of the main
1852 program does not catch exceptions.
1853
1854 This variable was added in Perl 5.004.
1855
1856 $WARNING
1857 $^W The current value of the warning switch, initially true if -w
1858 was used, false otherwise, but directly modifiable.
1859
1860 See also warnings.
1861
1862 Mnemonic: related to the -w switch.
1863
1864 ${^WARNING_BITS}
1865 The current set of warning checks enabled by the "use warnings"
1866 pragma. It has the same scoping as the $^H and "%^H"
1867 variables. The exact values are considered internal to the
1868 warnings pragma and may change between versions of Perl.
1869
1870 Each time a statement completes being compiled, the current
1871 value of "${^WARNING_BITS}" is stored with that statement, and
1872 can later be retrieved via "(caller($level))[9]".
1873
1874 This variable was added in Perl v5.6.0.
1875
1876 $OS_ERROR
1877 $ERRNO
1878 $! When referenced, $! retrieves the current value of the C
1879 "errno" integer variable. If $! is assigned a numerical value,
1880 that value is stored in "errno". When referenced as a string,
1881 $! yields the system error string corresponding to "errno".
1882
1883 Many system or library calls set "errno" if they fail, to
1884 indicate the cause of failure. They usually do not set "errno"
1885 to zero if they succeed and may set "errno" to a non-zero value
1886 on success. This means "errno", hence $!, is meaningful only
1887 immediately after a failure:
1888
1889 if (open my $fh, "<", $filename) {
1890 # Here $! is meaningless.
1891 ...
1892 }
1893 else {
1894 # ONLY here is $! meaningful.
1895 ...
1896 # Already here $! might be meaningless.
1897 }
1898 # Since here we might have either success or failure,
1899 # $! is meaningless.
1900
1901 Here, meaningless means that $! may be unrelated to the outcome
1902 of the open() operator. Assignment to $! is similarly
1903 ephemeral. It can be used immediately before invoking the
1904 die() operator, to set the exit value, or to inspect the system
1905 error string corresponding to error n, or to restore $! to a
1906 meaningful state.
1907
1908 Perl itself may set "errno" to a non-zero on failure even if no
1909 system call is performed.
1910
1911 Mnemonic: What just went bang?
1912
1913 %OS_ERROR
1914 %ERRNO
1915 %! Each element of "%!" has a true value only if $! is set to that
1916 value. For example, $!{ENOENT} is true if and only if the
1917 current value of $! is "ENOENT"; that is, if the most recent
1918 error was "No such file or directory" (or its moral equivalent:
1919 not all operating systems give that exact error, and certainly
1920 not all languages). The specific true value is not guaranteed,
1921 but in the past has generally been the numeric value of $!. To
1922 check if a particular key is meaningful on your system, use
1923 "exists $!{the_key}"; for a list of legal keys, use "keys %!".
1924 See Errno for more information, and also see "$!".
1925
1926 This variable was added in Perl 5.005.
1927
1928 $CHILD_ERROR
1929 $? The status returned by the last pipe close, backtick (``)
1930 command, successful call to wait() or waitpid(), or from the
1931 system() operator. This is just the 16-bit status word
1932 returned by the traditional Unix wait() system call (or else is
1933 made up to look like it). Thus, the exit value of the
1934 subprocess is really ($? >> 8), and "$? & 127" gives which
1935 signal, if any, the process died from, and "$? & 128" reports
1936 whether there was a core dump.
1937
1938 Additionally, if the "h_errno" variable is supported in C, its
1939 value is returned via $? if any "gethost*()" function fails.
1940
1941 If you have installed a signal handler for "SIGCHLD", the value
1942 of $? will usually be wrong outside that handler.
1943
1944 Inside an "END" subroutine $? contains the value that is going
1945 to be given to exit(). You can modify $? in an "END"
1946 subroutine to change the exit status of your program. For
1947 example:
1948
1949 END {
1950 $? = 1 if $? == 255; # die would make it 255
1951 }
1952
1953 Under VMS, the pragma "use vmsish 'status'" makes $? reflect
1954 the actual VMS exit status, instead of the default emulation of
1955 POSIX status; see "$?" in perlvms for details.
1956
1957 Mnemonic: similar to sh and ksh.
1958
1959 $EVAL_ERROR
1960 $@ The Perl error from the last "eval" operator, i.e. the last
1961 exception that was caught. For "eval BLOCK", this is either a
1962 runtime error message or the string or reference "die" was
1963 called with. The "eval STRING" form also catches syntax errors
1964 and other compile time exceptions.
1965
1966 If no error occurs, "eval" sets $@ to the empty string.
1967
1968 Warning messages are not collected in this variable. You can,
1969 however, set up a routine to process warnings by setting
1970 $SIG{__WARN__} as described in "%SIG".
1971
1972 Mnemonic: Where was the error "at"?
1973
1974 Variables related to the interpreter state
1975 These variables provide information about the current interpreter
1976 state.
1977
1978 $COMPILING
1979 $^C The current value of the flag associated with the -c switch.
1980 Mainly of use with -MO=... to allow code to alter its behavior
1981 when being compiled, such as for example to "AUTOLOAD" at
1982 compile time rather than normal, deferred loading. Setting
1983 "$^C = 1" is similar to calling "B::minus_c".
1984
1985 This variable was added in Perl v5.6.0.
1986
1987 $DEBUGGING
1988 $^D The current value of the debugging flags. May be read or set.
1989 Like its command-line equivalent, you can use numeric or
1990 symbolic values, e.g. "$^D = 10" or "$^D = "st"". See
1991 "-Dnumber" in perlrun. The contents of this variable also
1992 affects the debugger operation. See "Debugger Internals" in
1993 perldebguts.
1994
1995 Mnemonic: value of -D switch.
1996
1997 ${^GLOBAL_PHASE}
1998 The current phase of the perl interpreter.
1999
2000 Possible values are:
2001
2002 CONSTRUCT
2003 The "PerlInterpreter*" is being constructed via
2004 "perl_construct". This value is mostly there for
2005 completeness and for use via the underlying C variable
2006 "PL_phase". It's not really possible for Perl code to
2007 be executed unless construction of the interpreter is
2008 finished.
2009
2010 START This is the global compile-time. That includes,
2011 basically, every "BEGIN" block executed directly or
2012 indirectly from during the compile-time of the top-
2013 level program.
2014
2015 This phase is not called "BEGIN" to avoid confusion
2016 with "BEGIN"-blocks, as those are executed during
2017 compile-time of any compilation unit, not just the top-
2018 level program. A new, localised compile-time entered
2019 at run-time, for example by constructs as "eval "use
2020 SomeModule"" are not global interpreter phases, and
2021 therefore aren't reflected by "${^GLOBAL_PHASE}".
2022
2023 CHECK Execution of any "CHECK" blocks.
2024
2025 INIT Similar to "CHECK", but for "INIT"-blocks, not "CHECK"
2026 blocks.
2027
2028 RUN The main run-time, i.e. the execution of
2029 "PL_main_root".
2030
2031 END Execution of any "END" blocks.
2032
2033 DESTRUCT
2034 Global destruction.
2035
2036 Also note that there's no value for UNITCHECK-blocks. That's
2037 because those are run for each compilation unit individually,
2038 and therefore is not a global interpreter phase.
2039
2040 Not every program has to go through each of the possible
2041 phases, but transition from one phase to another can only
2042 happen in the order described in the above list.
2043
2044 An example of all of the phases Perl code can see:
2045
2046 BEGIN { print "compile-time: ${^GLOBAL_PHASE}\n" }
2047
2048 INIT { print "init-time: ${^GLOBAL_PHASE}\n" }
2049
2050 CHECK { print "check-time: ${^GLOBAL_PHASE}\n" }
2051
2052 {
2053 package Print::Phase;
2054
2055 sub new {
2056 my ($class, $time) = @_;
2057 return bless \$time, $class;
2058 }
2059
2060 sub DESTROY {
2061 my $self = shift;
2062 print "$$self: ${^GLOBAL_PHASE}\n";
2063 }
2064 }
2065
2066 print "run-time: ${^GLOBAL_PHASE}\n";
2067
2068 my $runtime = Print::Phase->new(
2069 "lexical variables are garbage collected before END"
2070 );
2071
2072 END { print "end-time: ${^GLOBAL_PHASE}\n" }
2073
2074 our $destruct = Print::Phase->new(
2075 "package variables are garbage collected after END"
2076 );
2077
2078 This will print out
2079
2080 compile-time: START
2081 check-time: CHECK
2082 init-time: INIT
2083 run-time: RUN
2084 lexical variables are garbage collected before END: RUN
2085 end-time: END
2086 package variables are garbage collected after END: DESTRUCT
2087
2088 This variable was added in Perl 5.14.0.
2089
2090 $^H WARNING: This variable is strictly for internal use only. Its
2091 availability, behavior, and contents are subject to change
2092 without notice.
2093
2094 This variable contains compile-time hints for the Perl
2095 interpreter. At the end of compilation of a BLOCK the value of
2096 this variable is restored to the value when the interpreter
2097 started to compile the BLOCK.
2098
2099 Each time a statement completes being compiled, the current
2100 value of $^H is stored with that statement, and can later be
2101 retrieved via "(caller($level))[8]". See "caller EXPR" in
2102 perlfunc.
2103
2104 When perl begins to parse any block construct that provides a
2105 lexical scope (e.g., eval body, required file, subroutine body,
2106 loop body, or conditional block), the existing value of $^H is
2107 saved, but its value is left unchanged. When the compilation
2108 of the block is completed, it regains the saved value. Between
2109 the points where its value is saved and restored, code that
2110 executes within BEGIN blocks is free to change the value of
2111 $^H.
2112
2113 This behavior provides the semantic of lexical scoping, and is
2114 used in, for instance, the "use strict" pragma.
2115
2116 The contents should be an integer; different bits of it are
2117 used for different pragmatic flags. Here's an example:
2118
2119 sub add_100 { $^H |= 0x100 }
2120
2121 sub foo {
2122 BEGIN { add_100() }
2123 bar->baz($boon);
2124 }
2125
2126 Consider what happens during execution of the BEGIN block. At
2127 this point the BEGIN block has already been compiled, but the
2128 body of foo() is still being compiled. The new value of $^H
2129 will therefore be visible only while the body of foo() is being
2130 compiled.
2131
2132 Substitution of "BEGIN { add_100() }" block with:
2133
2134 BEGIN { require strict; strict->import('vars') }
2135
2136 demonstrates how "use strict 'vars'" is implemented. Here's a
2137 conditional version of the same lexical pragma:
2138
2139 BEGIN {
2140 require strict; strict->import('vars') if $condition
2141 }
2142
2143 This variable was added in Perl 5.003.
2144
2145 %^H The "%^H" hash provides the same scoping semantics as $^H.
2146 This makes it useful for implementing lexically scoped pragmas.
2147 See perlpragma. All the entries are stringified when accessed
2148 at runtime, so only simple values can be accommodated. This
2149 means no references to objects, for example.
2150
2151 Each time a statement completes being compiled, the current
2152 value of "%^H" is stored with that statement, and can later be
2153 retrieved via "(caller($level))[10]". See "caller EXPR" in
2154 perlfunc.
2155
2156 When putting items into "%^H", in order to avoid conflicting
2157 with other users of the hash there is a convention regarding
2158 which keys to use. A module should use only keys that begin
2159 with the module's name (the name of its main package) and a "/"
2160 character. For example, a module "Foo::Bar" should use keys
2161 such as "Foo::Bar/baz".
2162
2163 This variable was added in Perl v5.6.0.
2164
2165 ${^OPEN}
2166 An internal variable used by PerlIO. A string in two parts,
2167 separated by a "\0" byte, the first part describes the input
2168 layers, the second part describes the output layers.
2169
2170 This is the mechanism that applies the lexical effects of the
2171 open pragma, and the main program scope effects of the "io" or
2172 "D" options for the -C command-line switch and PERL_UNICODE
2173 environment variable.
2174
2175 The functions accept(), open(), pipe(), readpipe() (as well as
2176 the related "qx" and `STRING` operators), socket(),
2177 socketpair(), and sysopen() are affected by the lexical value
2178 of this variable. The implicit "ARGV" handle opened by
2179 readline() (or the related "<>" and "<<>>" operators) on passed
2180 filenames is also affected (but not if it opens "STDIN"). If
2181 this variable is not set, these functions will set the default
2182 layers as described in "Defaults and how to override them" in
2183 PerlIO.
2184
2185 open() ignores this variable (and the default layers) when
2186 called with 3 arguments and explicit layers are specified.
2187 Indirect calls to these functions via modules like IO::Handle
2188 are not affected as they occur in a different lexical scope.
2189 Directory handles such as opened by opendir() are not currently
2190 affected.
2191
2192 This variable was added in Perl v5.8.0.
2193
2194 $PERLDB
2195 $^P The internal variable for debugging support. The meanings of
2196 the various bits are subject to change, but currently indicate:
2197
2198 0x01 Debug subroutine enter/exit.
2199
2200 0x02 Line-by-line debugging. Causes DB::DB() subroutine to be
2201 called for each statement executed. Also causes saving
2202 source code lines (like 0x400).
2203
2204 0x04 Switch off optimizations.
2205
2206 0x08 Preserve more data for future interactive inspections.
2207
2208 0x10 Keep info about source lines on which a subroutine is
2209 defined.
2210
2211 0x20 Start with single-step on.
2212
2213 0x40 Use subroutine address instead of name when reporting.
2214
2215 0x80 Report "goto &subroutine" as well.
2216
2217 0x100 Provide informative "file" names for evals based on the
2218 place they were compiled.
2219
2220 0x200 Provide informative names to anonymous subroutines based
2221 on the place they were compiled.
2222
2223 0x400 Save source code lines into "@{"_<$filename"}".
2224
2225 0x800 When saving source, include evals that generate no
2226 subroutines.
2227
2228 0x1000
2229 When saving source, include source that did not compile.
2230
2231 Some bits may be relevant at compile-time only, some at run-
2232 time only. This is a new mechanism and the details may change.
2233 See also perldebguts.
2234
2235 ${^TAINT}
2236 Reflects if taint mode is on or off. 1 for on (the program was
2237 run with -T), 0 for off, -1 when only taint warnings are
2238 enabled (i.e. with -t or -TU).
2239
2240 Note: if your perl was built without taint support (see
2241 perlsec), then "${^TAINT}" will always be 0, even if the
2242 program was run with -T).
2243
2244 This variable is read-only.
2245
2246 This variable was added in Perl v5.8.0.
2247
2248 ${^SAFE_LOCALES}
2249 Reflects if safe locale operations are available to this perl
2250 (when the value is 1) or not (the value is 0). This variable
2251 is always 1 if the perl has been compiled without threads. It
2252 is also 1 if this perl is using thread-safe locale operations.
2253 Note that an individual thread may choose to use the global
2254 locale (generally unsafe) by calling "switch_to_global_locale"
2255 in perlapi. This variable currently is still set to 1 in such
2256 threads.
2257
2258 This variable is read-only.
2259
2260 This variable was added in Perl v5.28.0.
2261
2262 ${^UNICODE}
2263 Reflects certain Unicode settings of Perl. See perlrun
2264 documentation for the "-C" switch for more information about
2265 the possible values.
2266
2267 This variable is set during Perl startup and is thereafter
2268 read-only.
2269
2270 This variable was added in Perl v5.8.2.
2271
2272 ${^UTF8CACHE}
2273 This variable controls the state of the internal UTF-8 offset
2274 caching code. 1 for on (the default), 0 for off, -1 to debug
2275 the caching code by checking all its results against linear
2276 scans, and panicking on any discrepancy.
2277
2278 This variable was added in Perl v5.8.9. It is subject to
2279 change or removal without notice, but is currently used to
2280 avoid recalculating the boundaries of multi-byte UTF-8-encoded
2281 characters.
2282
2283 ${^UTF8LOCALE}
2284 This variable indicates whether a UTF-8 locale was detected by
2285 perl at startup. This information is used by perl when it's in
2286 adjust-utf8ness-to-locale mode (as when run with the "-CL"
2287 command-line switch); see perlrun for more info on this.
2288
2289 This variable was added in Perl v5.8.8.
2290
2291 Deprecated and removed variables
2292 Deprecating a variable announces the intent of the perl maintainers to
2293 eventually remove the variable from the language. It may still be
2294 available despite its status. Using a deprecated variable triggers a
2295 warning.
2296
2297 Once a variable is removed, its use triggers an error telling you the
2298 variable is unsupported.
2299
2300 See perldiag for details about error messages.
2301
2302 $# $# was a variable that could be used to format printed numbers.
2303 After a deprecation cycle, its magic was removed in Perl
2304 v5.10.0 and using it now triggers a warning: "$# is no longer
2305 supported".
2306
2307 This is not the sigil you use in front of an array name to get
2308 the last index, like $#array. That's still how you get the
2309 last index of an array in Perl. The two have nothing to do
2310 with each other.
2311
2312 Deprecated in Perl 5.
2313
2314 Removed in Perl v5.10.0.
2315
2316 $* $* was a variable that you could use to enable multiline
2317 matching. After a deprecation cycle, its magic was removed in
2318 Perl v5.10.0. Using it now triggers a warning: "$* is no
2319 longer supported". You should use the "/s" and "/m" regexp
2320 modifiers instead.
2321
2322 Deprecated in Perl 5.
2323
2324 Removed in Perl v5.10.0.
2325
2326 $[ This variable stores the index of the first element in an
2327 array, and of the first character in a substring. The default
2328 is 0, but you could theoretically set it to 1 to make Perl
2329 behave more like awk (or Fortran) when subscripting and when
2330 evaluating the index() and substr() functions.
2331
2332 As of release 5 of Perl, assignment to $[ is treated as a
2333 compiler directive, and cannot influence the behavior of any
2334 other file. (That's why you can only assign compile-time
2335 constants to it.) Its use is highly discouraged.
2336
2337 Prior to Perl v5.10.0, assignment to $[ could be seen from
2338 outer lexical scopes in the same file, unlike other compile-
2339 time directives (such as strict). Using local() on it would
2340 bind its value strictly to a lexical block. Now it is always
2341 lexically scoped.
2342
2343 As of Perl v5.16.0, it is implemented by the arybase module.
2344
2345 As of Perl v5.30.0, or under "use v5.16", or "no feature
2346 "array_base"", $[ no longer has any effect, and always contains
2347 0. Assigning 0 to it is permitted, but any other value will
2348 produce an error.
2349
2350 Mnemonic: [ begins subscripts.
2351
2352 Deprecated in Perl v5.12.0.
2353
2354 ${^ENCODING}
2355 This variable is no longer supported.
2356
2357 It used to hold the object reference to the "Encode" object
2358 that was used to convert the source code to Unicode.
2359
2360 Its purpose was to allow your non-ASCII Perl scripts not to
2361 have to be written in UTF-8; this was useful before editors
2362 that worked on UTF-8 encoded text were common, but that was
2363 long ago. It caused problems, such as affecting the operation
2364 of other modules that weren't expecting it, causing general
2365 mayhem.
2366
2367 If you need something like this functionality, it is
2368 recommended that use you a simple source filter, such as
2369 Filter::Encoding.
2370
2371 If you are coming here because code of yours is being adversely
2372 affected by someone's use of this variable, you can usually
2373 work around it by doing this:
2374
2375 local ${^ENCODING};
2376
2377 near the beginning of the functions that are getting broken.
2378 This undefines the variable during the scope of execution of
2379 the including function.
2380
2381 This variable was added in Perl 5.8.2 and removed in 5.26.0.
2382 Setting it to anything other than "undef" was made fatal in
2383 Perl 5.28.0.
2384
2385 ${^WIN32_SLOPPY_STAT}
2386 This variable no longer has any function.
2387
2388 This variable was added in Perl v5.10.0 and removed in Perl
2389 v5.34.0.
2390
2391
2392
2393perl v5.38.2 2023-11-30 PERLVAR(1)