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