3 perlvar - Perl predefined variables
7 =head2 Predefined Names
9 The following names have special meaning to Perl. Most
10 punctuation names have reasonable mnemonics, or analogs in the
11 shells. Nevertheless, if you wish to use long variable names,
16 at the top of your program. This aliases all the short names to the long
17 names in the current package. Some even have medium names, generally
18 borrowed from B<awk>. In general, it's best to use the
20 use English '-no_match_vars';
22 invocation if you don't need $PREMATCH, $MATCH, or $POSTMATCH, as it avoids
23 a certain performance hit with the use of regular expressions. See
26 Variables that depend on the currently selected filehandle may be set by
27 calling an appropriate object method on the IO::Handle object, although
28 this is less efficient than using the regular built-in variables. (Summary
29 lines below for this contain the word HANDLE.) First you must say
33 after which you may use either
41 Each method returns the old value of the IO::Handle attribute.
42 The methods each take an optional EXPR, which, if supplied, specifies the
43 new value for the IO::Handle attribute in question. If not supplied,
44 most methods do nothing to the current value--except for
45 autoflush(), which will assume a 1 for you, just to be different.
47 Because loading in the IO::Handle class is an expensive operation, you should
48 learn how to use the regular built-in variables.
50 A few of these variables are considered "read-only". This means that if
51 you try to assign to this variable, either directly or indirectly through
52 a reference, you'll raise a run-time exception.
54 You should be very careful when modifying the default values of most
55 special variables described in this document. In most cases you want
56 to localize these variables before changing them, since if you don't,
57 the change may affect other modules which rely on the default values
58 of the special variables that you have changed. This is one of the
59 correct ways to read the whole file at once:
61 open my $fh, "foo" or die $!;
62 local $/; # enable localized slurp mode
66 But the following code is quite bad:
68 open my $fh, "foo" or die $!;
69 undef $/; # enable slurp mode
73 since some other module, may want to read data from some file in the
74 default "line mode", so if the code we have just presented has been
75 executed, the global value of C<$/> is now changed for any other code
76 running inside the same Perl interpreter.
78 Usually when a variable is localized you want to make sure that this
79 change affects the shortest scope possible. So unless you are already
80 inside some short C<{}> block, you should create one yourself. For
84 open my $fh, "foo" or die $!;
91 Here is an example of how your own code can go broken:
99 # do something with $_
102 You probably expect this code to print:
110 Why? Because nasty_break() modifies C<$_> without localizing it
111 first. The fix is to add local():
115 It's easy to notice the problem in such a short example, but in more
116 complicated code you are looking for trouble if you don't localize
117 changes to the special variables.
119 The following list is ordered by scalar variables first, then the
120 arrays, then the hashes.
128 The default input and pattern-searching space. The following pairs are
131 while (<>) {...} # equivalent only in while!
132 while (defined($_ = <>)) {...}
143 Here are the places where Perl will assume $_ even if you
150 Various unary functions, including functions like ord() and int(), as well
151 as the all file tests (C<-f>, C<-d>) except for C<-t>, which defaults to
156 Various list functions like print() and unlink().
160 The pattern matching operations C<m//>, C<s///>, and C<tr///> when used
161 without an C<=~> operator.
165 The default iterator variable in a C<foreach> loop if no other
166 variable is supplied.
170 The implicit iterator variable in the grep() and map() functions.
174 The default place to put an input record when a C<< <FH> >>
175 operation's result is tested by itself as the sole criterion of a C<while>
176 test. Outside a C<while> test, this will not happen.
180 (Mnemonic: underline is understood in certain operations.)
190 Special package variables when using sort(), see L<perlfunc/sort>.
191 Because of this specialness $a and $b don't need to be declared
192 (using local(), use vars, or our()) even when using the strict
193 vars pragma. Don't lexicalize them with C<my $a> or C<my $b>
194 if you want to be able to use them in the sort() comparison block
203 Contains the subpattern from the corresponding set of capturing
204 parentheses from the last pattern match, not counting patterns
205 matched in nested blocks that have been exited already. (Mnemonic:
206 like \digits.) These variables are all read-only and dynamically
207 scoped to the current BLOCK.
213 The string matched by the last successful pattern match (not counting
214 any matches hidden within a BLOCK or eval() enclosed by the current
215 BLOCK). (Mnemonic: like & in some editors.) This variable is read-only
216 and dynamically scoped to the current BLOCK.
218 The use of this variable anywhere in a program imposes a considerable
219 performance penalty on all regular expression matches. See L</BUGS>.
225 The string preceding whatever was matched by the last successful
226 pattern match (not counting any matches hidden within a BLOCK or eval
227 enclosed by the current BLOCK). (Mnemonic: C<`> often precedes a quoted
228 string.) This variable is read-only.
230 The use of this variable anywhere in a program imposes a considerable
231 performance penalty on all regular expression matches. See L</BUGS>.
237 The string following whatever was matched by the last successful
238 pattern match (not counting any matches hidden within a BLOCK or eval()
239 enclosed by the current BLOCK). (Mnemonic: C<'> often follows a quoted
242 local $_ = 'abcdefghi';
244 print "$`:$&:$'\n"; # prints abc:def:ghi
246 This variable is read-only and dynamically scoped to the current BLOCK.
248 The use of this variable anywhere in a program imposes a considerable
249 performance penalty on all regular expression matches. See L</BUGS>.
251 =item $LAST_PAREN_MATCH
255 The text matched by the last bracket of the last successful search pattern.
256 This is useful if you don't know which one of a set of alternative patterns
257 matched. For example:
259 /Version: (.*)|Revision: (.*)/ && ($rev = $+);
261 (Mnemonic: be positive and forward looking.)
262 This variable is read-only and dynamically scoped to the current BLOCK.
266 The text matched by the used group most-recently closed (i.e. the group
267 with the rightmost closing parenthesis) of the last successful search
268 pattern. (Mnemonic: the (possibly) Nested parenthesis that most
271 This is primarily used inside C<(?{...})> blocks for examining text
272 recently matched. For example, to effectively capture text to a variable
273 (in addition to C<$1>, C<$2>, etc.), replace C<(...)> with
275 (?:(...)(?{ $var = $^N }))
277 By setting and then using C<$var> in this way relieves you from having to
278 worry about exactly which numbered set of parentheses they are.
280 This variable is dynamically scoped to the current BLOCK.
282 =item @LAST_MATCH_END
286 This array holds the offsets of the ends of the last successful
287 submatches in the currently active dynamic scope. C<$+[0]> is
288 the offset into the string of the end of the entire match. This
289 is the same value as what the C<pos> function returns when called
290 on the variable that was matched against. The I<n>th element
291 of this array holds the offset of the I<n>th submatch, so
292 C<$+[1]> is the offset past where $1 ends, C<$+[2]> the offset
293 past where $2 ends, and so on. You can use C<$#+> to determine
294 how many subgroups were in the last successful match. See the
295 examples given for the C<@-> variable.
297 =item HANDLE->input_line_number(EXPR)
299 =item $INPUT_LINE_NUMBER
305 Current line number for the last filehandle accessed.
307 Each filehandle in Perl counts the number of lines that have been read
308 from it. (Depending on the value of C<$/>, Perl's idea of what
309 constitutes a line may not match yours.) When a line is read from a
310 filehandle (via readline() or C<< <> >>), or when tell() or seek() is
311 called on it, C<$.> becomes an alias to the line counter for that
314 You can adjust the counter by assigning to C<$.>, but this will not
315 actually move the seek pointer. I<Localizing C<$.> will not localize
316 the filehandle's line count>. Instead, it will localize perl's notion
317 of which filehandle C<$.> is currently aliased to.
319 C<$.> is reset when the filehandle is closed, but B<not> when an open
320 filehandle is reopened without an intervening close(). For more
321 details, see L<perlop/"IE<sol>O Operators">. Because C<< <> >> never does
322 an explicit close, line numbers increase across ARGV files (but see
323 examples in L<perlfunc/eof>).
325 You can also use C<< HANDLE->input_line_number(EXPR) >> to access the
326 line counter for a given filehandle without having to worry about
327 which handle you last accessed.
329 (Mnemonic: many programs use "." to mean the current line number.)
331 =item IO::Handle->input_record_separator(EXPR)
333 =item $INPUT_RECORD_SEPARATOR
339 The input record separator, newline by default. This
340 influences Perl's idea of what a "line" is. Works like B<awk>'s RS
341 variable, including treating empty lines as a terminator if set to
342 the null string. (An empty line cannot contain any spaces
343 or tabs.) You may set it to a multi-character string to match a
344 multi-character terminator, or to C<undef> to read through the end
345 of file. Setting it to C<"\n\n"> means something slightly
346 different than setting to C<"">, if the file contains consecutive
347 empty lines. Setting to C<""> will treat two or more consecutive
348 empty lines as a single empty line. Setting to C<"\n\n"> will
349 blindly assume that the next input character belongs to the next
350 paragraph, even if it's a newline. (Mnemonic: / delimits
351 line boundaries when quoting poetry.)
353 local $/; # enable "slurp" mode
354 local $_ = <FH>; # whole file now here
357 Remember: the value of C<$/> is a string, not a regex. B<awk> has to be
358 better for something. :-)
360 Setting C<$/> to a reference to an integer, scalar containing an integer, or
361 scalar that's convertible to an integer will attempt to read records
362 instead of lines, with the maximum record size being the referenced
365 local $/ = \32768; # or \"32768", or \$var_containing_32768
366 open my $fh, $myfile or die $!;
369 will read a record of no more than 32768 bytes from FILE. If you're
370 not reading from a record-oriented file (or your OS doesn't have
371 record-oriented files), then you'll likely get a full chunk of data
372 with every read. If a record is larger than the record size you've
373 set, you'll get the record back in pieces.
375 On VMS, record reads are done with the equivalent of C<sysread>,
376 so it's best not to mix record and non-record reads on the same
377 file. (This is unlikely to be a problem, because any file you'd
378 want to read in record mode is probably unusable in line mode.)
379 Non-VMS systems do normal I/O, so it's safe to mix record and
380 non-record reads of a file.
382 See also L<perlport/"Newlines">. Also see C<$.>.
384 =item HANDLE->autoflush(EXPR)
386 =item $OUTPUT_AUTOFLUSH
390 If set to nonzero, forces a flush right away and after every write
391 or print on the currently selected output channel. Default is 0
392 (regardless of whether the channel is really buffered by the
393 system or not; C<$|> tells you only whether you've asked Perl
394 explicitly to flush after each write). STDOUT will
395 typically be line buffered if output is to the terminal and block
396 buffered otherwise. Setting this variable is useful primarily when
397 you are outputting to a pipe or socket, such as when you are running
398 a Perl program under B<rsh> and want to see the output as it's
399 happening. This has no effect on input buffering. See L<perlfunc/getc>
400 for that. (Mnemonic: when you want your pipes to be piping hot.)
402 =item IO::Handle->output_field_separator EXPR
404 =item $OUTPUT_FIELD_SEPARATOR
410 The output field separator for the print operator. Ordinarily the
411 print operator simply prints out its arguments without further
412 adornment. To get behavior more like B<awk>, set this variable as
413 you would set B<awk>'s OFS variable to specify what is printed
414 between fields. (Mnemonic: what is printed when there is a "," in
415 your print statement.)
417 =item IO::Handle->output_record_separator EXPR
419 =item $OUTPUT_RECORD_SEPARATOR
425 The output record separator for the print operator. Ordinarily the
426 print operator simply prints out its arguments as is, with no
427 trailing newline or other end-of-record string added. To get
428 behavior more like B<awk>, set this variable as you would set
429 B<awk>'s ORS variable to specify what is printed at the end of the
430 print. (Mnemonic: you set C<$\> instead of adding "\n" at the
431 end of the print. Also, it's just like C<$/>, but it's what you
432 get "back" from Perl.)
434 =item $LIST_SEPARATOR
438 This is like C<$,> except that it applies to array and slice values
439 interpolated into a double-quoted string (or similar interpreted
440 string). Default is a space. (Mnemonic: obvious, I think.)
442 =item $SUBSCRIPT_SEPARATOR
448 The subscript separator for multidimensional array emulation. If you
449 refer to a hash element as
455 $foo{join($;, $a, $b, $c)}
459 @foo{$a,$b,$c} # a slice--note the @
463 ($foo{$a},$foo{$b},$foo{$c})
465 Default is "\034", the same as SUBSEP in B<awk>. If your
466 keys contain binary data there might not be any safe value for C<$;>.
467 (Mnemonic: comma (the syntactic subscript separator) is a
468 semi-semicolon. Yeah, I know, it's pretty lame, but C<$,> is already
469 taken for something more important.)
471 Consider using "real" multidimensional arrays as described
476 The output format for printed numbers. This variable is a half-hearted
477 attempt to emulate B<awk>'s OFMT variable. There are times, however,
478 when B<awk> and Perl have differing notions of what counts as
479 numeric. The initial value is "%.I<n>g", where I<n> is the value
480 of the macro DBL_DIG from your system's F<float.h>. This is different from
481 B<awk>'s default OFMT setting of "%.6g", so you need to set C<$#>
482 explicitly to get B<awk>'s value. (Mnemonic: # is the number sign.)
484 Use of C<$#> is deprecated.
486 =item HANDLE->format_page_number(EXPR)
488 =item $FORMAT_PAGE_NUMBER
492 The current page number of the currently selected output channel.
494 (Mnemonic: % is page number in B<nroff>.)
496 =item HANDLE->format_lines_per_page(EXPR)
498 =item $FORMAT_LINES_PER_PAGE
502 The current page length (printable lines) of the currently selected
503 output channel. Default is 60.
505 (Mnemonic: = has horizontal lines.)
507 =item HANDLE->format_lines_left(EXPR)
509 =item $FORMAT_LINES_LEFT
513 The number of lines left on the page of the currently selected output
516 (Mnemonic: lines_on_page - lines_printed.)
518 =item @LAST_MATCH_START
522 $-[0] is the offset of the start of the last successful match.
523 C<$-[>I<n>C<]> is the offset of the start of the substring matched by
524 I<n>-th subpattern, or undef if the subpattern did not match.
526 Thus after a match against $_, $& coincides with C<substr $_, $-[0],
527 $+[0] - $-[0]>. Similarly, C<$>I<n> coincides with C<substr $_, $-[>I<n>C<],
528 $+[>I<n>C<] - $-[>I<n>C<]> if C<$-[>I<n>C<]> is defined, and $+ coincides with
529 C<substr $_, $-[$#-], $+[$#-]>. One can use C<$#-> to find the last
530 matched subgroup in the last successful match. Contrast with
531 C<$#+>, the number of subgroups in the regular expression. Compare
534 This array holds the offsets of the beginnings of the last
535 successful submatches in the currently active dynamic scope.
536 C<$-[0]> is the offset into the string of the beginning of the
537 entire match. The I<n>th element of this array holds the offset
538 of the I<n>th submatch, so C<$-[1]> is the offset where $1
539 begins, C<$-[2]> the offset where $2 begins, and so on.
541 After a match against some variable $var:
545 =item C<$`> is the same as C<substr($var, 0, $-[0])>
547 =item C<$&> is the same as C<substr($var, $-[0], $+[0] - $-[0])>
549 =item C<$'> is the same as C<substr($var, $+[0])>
551 =item C<$1> is the same as C<substr($var, $-[1], $+[1] - $-[1])>
553 =item C<$2> is the same as C<substr($var, $-[2], $+[2] - $-[2])>
555 =item C<$3> is the same as C<substr $var, $-[3], $+[3] - $-[3])>
559 =item HANDLE->format_name(EXPR)
565 The name of the current report format for the currently selected output
566 channel. Default is the name of the filehandle. (Mnemonic: brother to
569 =item HANDLE->format_top_name(EXPR)
571 =item $FORMAT_TOP_NAME
575 The name of the current top-of-page format for the currently selected
576 output channel. Default is the name of the filehandle with _TOP
577 appended. (Mnemonic: points to top of page.)
579 =item IO::Handle->format_line_break_characters EXPR
581 =item $FORMAT_LINE_BREAK_CHARACTERS
585 The current set of characters after which a string may be broken to
586 fill continuation fields (starting with ^) in a format. Default is
587 S<" \n-">, to break on whitespace or hyphens. (Mnemonic: a "colon" in
588 poetry is a part of a line.)
590 =item IO::Handle->format_formfeed EXPR
592 =item $FORMAT_FORMFEED
596 What formats output as a form feed. Default is \f.
602 The current value of the write() accumulator for format() lines. A format
603 contains formline() calls that put their result into C<$^A>. After
604 calling its format, write() prints out the contents of C<$^A> and empties.
605 So you never really see the contents of C<$^A> unless you call
606 formline() yourself and then look at it. See L<perlform> and
607 L<perlfunc/formline()>.
613 The status returned by the last pipe close, backtick (C<``>) command,
614 successful call to wait() or waitpid(), or from the system()
615 operator. This is just the 16-bit status word returned by the
616 wait() system call (or else is made up to look like it). Thus, the
617 exit value of the subprocess is really (C<<< $? >> 8 >>>), and
618 C<$? & 127> gives which signal, if any, the process died from, and
619 C<$? & 128> reports whether there was a core dump. (Mnemonic:
620 similar to B<sh> and B<ksh>.)
622 Additionally, if the C<h_errno> variable is supported in C, its value
623 is returned via $? if any C<gethost*()> function fails.
625 If you have installed a signal handler for C<SIGCHLD>, the
626 value of C<$?> will usually be wrong outside that handler.
628 Inside an C<END> subroutine C<$?> contains the value that is going to be
629 given to C<exit()>. You can modify C<$?> in an C<END> subroutine to
630 change the exit status of your program. For example:
633 $? = 1 if $? == 255; # die would make it 255
636 Under VMS, the pragma C<use vmsish 'status'> makes C<$?> reflect the
637 actual VMS exit status, instead of the default emulation of POSIX
638 status; see L<perlvms/$?> for details.
640 Also see L<Error Indicators>.
644 The I<object reference> to the Encode object that is used to convert
645 the source code to Unicode. Thanks to this variable your perl script
646 does not have to be written in UTF-8. Default is I<undef>. The direct
647 manipulation of this variable is highly discouraged. See L<encoding>
656 If used numerically, yields the current value of the C C<errno>
657 variable, or in other words, if a system or library call fails, it
658 sets this variable. This means that the value of C<$!> is meaningful
659 only I<immediately> after a B<failure>:
661 if (open(FH, $filename)) {
662 # Here $! is meaningless.
665 # ONLY here is $! meaningful.
667 # Already here $! might be meaningless.
669 # Since here we might have either success or failure,
670 # here $! is meaningless.
672 In the above I<meaningless> stands for anything: zero, non-zero,
673 C<undef>. A successful system or library call does B<not> set
674 the variable to zero.
676 If used as a string, yields the corresponding system error string.
677 You can assign a number to C<$!> to set I<errno> if, for instance,
678 you want C<"$!"> to return the string for error I<n>, or you want
679 to set the exit value for the die() operator. (Mnemonic: What just
682 Also see L<Error Indicators>.
686 Each element of C<%!> has a true value only if C<$!> is set to that
687 value. For example, C<$!{ENOENT}> is true if and only if the current
688 value of C<$!> is C<ENOENT>; that is, if the most recent error was
689 "No such file or directory" (or its moral equivalent: not all operating
690 systems give that exact error, and certainly not all languages).
691 To check if a particular key is meaningful on your system, use
692 C<exists $!{the_key}>; for a list of legal keys, use C<keys %!>.
693 See L<Errno> for more information, and also see above for the
696 =item $EXTENDED_OS_ERROR
700 Error information specific to the current operating system. At
701 the moment, this differs from C<$!> under only VMS, OS/2, and Win32
702 (and for MacPerl). On all other platforms, C<$^E> is always just
705 Under VMS, C<$^E> provides the VMS status value from the last
706 system error. This is more specific information about the last
707 system error than that provided by C<$!>. This is particularly
708 important when C<$!> is set to B<EVMSERR>.
710 Under OS/2, C<$^E> is set to the error code of the last call to
711 OS/2 API either via CRT, or directly from perl.
713 Under Win32, C<$^E> always returns the last error information
714 reported by the Win32 call C<GetLastError()> which describes
715 the last error from within the Win32 API. Most Win32-specific
716 code will report errors via C<$^E>. ANSI C and Unix-like calls
717 set C<errno> and so most portable Perl code will report errors
720 Caveats mentioned in the description of C<$!> generally apply to
721 C<$^E>, also. (Mnemonic: Extra error explanation.)
723 Also see L<Error Indicators>.
729 The Perl syntax error message from the last eval() operator.
730 If $@ is the null string, the last eval() parsed and executed
731 correctly (although the operations you invoked may have failed in the
732 normal fashion). (Mnemonic: Where was the syntax error "at"?)
734 Warning messages are not collected in this variable. You can,
735 however, set up a routine to process warnings by setting C<$SIG{__WARN__}>
738 Also see L<Error Indicators>.
746 The process number of the Perl running this script. You should
747 consider this variable read-only, although it will be altered
748 across fork() calls. (Mnemonic: same as shells.)
750 Note for Linux users: on Linux, the C functions C<getpid()> and
751 C<getppid()> return different values from different threads. In order to
752 be portable, this behavior is not reflected by C<$$>, whose value remains
753 consistent across threads. If you want to call the underlying C<getpid()>,
754 you may use the CPAN module C<Linux::Pid>.
762 The real uid of this process. (Mnemonic: it's the uid you came I<from>,
763 if you're running setuid.) You can change both the real uid and
764 the effective uid at the same time by using POSIX::setuid().
766 =item $EFFECTIVE_USER_ID
772 The effective uid of this process. Example:
774 $< = $>; # set real to effective uid
775 ($<,$>) = ($>,$<); # swap real and effective uid
777 You can change both the effective uid and the real uid at the same
778 time by using POSIX::setuid().
780 (Mnemonic: it's the uid you went I<to>, if you're running setuid.)
781 C<< $< >> and C<< $> >> can be swapped only on machines
782 supporting setreuid().
790 The real gid of this process. If you are on a machine that supports
791 membership in multiple groups simultaneously, gives a space separated
792 list of groups you are in. The first number is the one returned by
793 getgid(), and the subsequent ones by getgroups(), one of which may be
794 the same as the first number.
796 However, a value assigned to C<$(> must be a single number used to
797 set the real gid. So the value given by C<$(> should I<not> be assigned
798 back to C<$(> without being forced numeric, such as by adding zero.
800 You can change both the real gid and the effective gid at the same
801 time by using POSIX::setgid().
803 (Mnemonic: parentheses are used to I<group> things. The real gid is the
804 group you I<left>, if you're running setgid.)
806 =item $EFFECTIVE_GROUP_ID
812 The effective gid of this process. If you are on a machine that
813 supports membership in multiple groups simultaneously, gives a space
814 separated list of groups you are in. The first number is the one
815 returned by getegid(), and the subsequent ones by getgroups(), one of
816 which may be the same as the first number.
818 Similarly, a value assigned to C<$)> must also be a space-separated
819 list of numbers. The first number sets the effective gid, and
820 the rest (if any) are passed to setgroups(). To get the effect of an
821 empty list for setgroups(), just repeat the new effective gid; that is,
822 to force an effective gid of 5 and an effectively empty setgroups()
823 list, say C< $) = "5 5" >.
825 You can change both the effective gid and the real gid at the same
826 time by using POSIX::setgid() (use only a single numeric argument).
828 (Mnemonic: parentheses are used to I<group> things. The effective gid
829 is the group that's I<right> for you, if you're running setgid.)
831 C<< $< >>, C<< $> >>, C<$(> and C<$)> can be set only on
832 machines that support the corresponding I<set[re][ug]id()> routine. C<$(>
833 and C<$)> can be swapped only on machines supporting setregid().
839 Contains the name of the program being executed.
841 On some (read: not all) operating systems assigning to C<$0> modifies
842 the argument area that the C<ps> program sees. On some platforms you
843 may have to use special C<ps> options or a different C<ps> to see the
844 changes. Modifying the $0 is more useful as a way of indicating the
845 current program state than it is for hiding the program you're
846 running. (Mnemonic: same as B<sh> and B<ksh>.)
848 Note that there are platform specific limitations on the the maximum
849 length of C<$0>. In the most extreme case it may be limited to the
850 space occupied by the original C<$0>.
852 In some platforms there may be arbitrary amount of padding, for
853 example space characters, after the modified name as shown by C<ps>.
854 In some platforms this padding may extend all the way to the original
855 length of the argument area, no matter what you do (this is the case
856 for example with Linux 2.2).
858 Note for BSD users: setting C<$0> does not completely remove "perl"
859 from the ps(1) output. For example, setting C<$0> to C<"foobar"> may
860 result in C<"perl: foobar (perl)"> (whether both the C<"perl: "> prefix
861 and the " (perl)" suffix are shown depends on your exact BSD variant
862 and version). This is an operating system feature, Perl cannot help it.
864 In multithreaded scripts Perl coordinates the threads so that any
865 thread may modify its copy of the C<$0> and the change becomes visible
866 to ps(1) (assuming the operating system plays along). Note that the
867 the view of C<$0> the other threads have will not change since they
868 have their own copies of it.
872 The index of the first element in an array, and of the first character
873 in a substring. Default is 0, but you could theoretically set it
874 to 1 to make Perl behave more like B<awk> (or Fortran) when
875 subscripting and when evaluating the index() and substr() functions.
876 (Mnemonic: [ begins subscripts.)
878 As of release 5 of Perl, assignment to C<$[> is treated as a compiler
879 directive, and cannot influence the behavior of any other file.
880 (That's why you can only assign compile-time constants to it.)
881 Its use is highly discouraged.
883 Note that, unlike other compile-time directives (such as L<strict>),
884 assignment to $[ can be seen from outer lexical scopes in the same file.
885 However, you can use local() on it to strictly bound its value to a
890 The version + patchlevel / 1000 of the Perl interpreter. This variable
891 can be used to determine whether the Perl interpreter executing a
892 script is in the right range of versions. (Mnemonic: Is this version
893 of perl in the right bracket?) Example:
895 warn "No checksumming!\n" if $] < 3.019;
897 See also the documentation of C<use VERSION> and C<require VERSION>
898 for a convenient way to fail if the running Perl interpreter is too old.
900 The floating point representation can sometimes lead to inaccurate
901 numeric comparisons. See C<$^V> for a more modern representation of
902 the Perl version that allows accurate string comparisons.
908 The current value of the flag associated with the B<-c> switch.
909 Mainly of use with B<-MO=...> to allow code to alter its behavior
910 when being compiled, such as for example to AUTOLOAD at compile
911 time rather than normal, deferred loading. See L<perlcc>. Setting
912 C<$^C = 1> is similar to calling C<B::minus_c>.
918 The current value of the debugging flags. (Mnemonic: value of B<-D>
919 switch.) May be read or set. Like its command-line equivalent, you can use
920 numeric or symbolic values, eg C<$^D = 10> or C<$^D = "st">.
926 The maximum system file descriptor, ordinarily 2. System file
927 descriptors are passed to exec()ed processes, while higher file
928 descriptors are not. Also, during an open(), system file descriptors are
929 preserved even if the open() fails. (Ordinary file descriptors are
930 closed before the open() is attempted.) The close-on-exec
931 status of a file descriptor will be decided according to the value of
932 C<$^F> when the corresponding file, pipe, or socket was opened, not the
937 WARNING: This variable is strictly for internal use only. Its availability,
938 behavior, and contents are subject to change without notice.
940 This variable contains compile-time hints for the Perl interpreter. At the
941 end of compilation of a BLOCK the value of this variable is restored to the
942 value when the interpreter started to compile the BLOCK.
944 When perl begins to parse any block construct that provides a lexical scope
945 (e.g., eval body, required file, subroutine body, loop body, or conditional
946 block), the existing value of $^H is saved, but its value is left unchanged.
947 When the compilation of the block is completed, it regains the saved value.
948 Between the points where its value is saved and restored, code that
949 executes within BEGIN blocks is free to change the value of $^H.
951 This behavior provides the semantic of lexical scoping, and is used in,
952 for instance, the C<use strict> pragma.
954 The contents should be an integer; different bits of it are used for
955 different pragmatic flags. Here's an example:
957 sub add_100 { $^H |= 0x100 }
964 Consider what happens during execution of the BEGIN block. At this point
965 the BEGIN block has already been compiled, but the body of foo() is still
966 being compiled. The new value of $^H will therefore be visible only while
967 the body of foo() is being compiled.
969 Substitution of the above BEGIN block with:
971 BEGIN { require strict; strict->import('vars') }
973 demonstrates how C<use strict 'vars'> is implemented. Here's a conditional
974 version of the same lexical pragma:
976 BEGIN { require strict; strict->import('vars') if $condition }
980 WARNING: This variable is strictly for internal use only. Its availability,
981 behavior, and contents are subject to change without notice.
983 The %^H hash provides the same scoping semantic as $^H. This makes it
984 useful for implementation of lexically scoped pragmas.
990 The current value of the inplace-edit extension. Use C<undef> to disable
991 inplace editing. (Mnemonic: value of B<-i> switch.)
995 By default, running out of memory is an untrappable, fatal error.
996 However, if suitably built, Perl can use the contents of C<$^M>
997 as an emergency memory pool after die()ing. Suppose that your Perl
998 were compiled with -DPERL_EMERGENCY_SBRK and used Perl's malloc.
1001 $^M = 'a' x (1 << 16);
1003 would allocate a 64K buffer for use in an emergency. See the
1004 F<INSTALL> file in the Perl distribution for information on how to
1005 enable this option. To discourage casual use of this advanced
1006 feature, there is no L<English|English> long name for this variable.
1012 The name of the operating system under which this copy of Perl was
1013 built, as determined during the configuration process. The value
1014 is identical to C<$Config{'osname'}>. See also L<Config> and the
1015 B<-V> command-line switch documented in L<perlrun>.
1017 In Windows platforms, $^O is not very helpful: since it is always
1018 C<MSWin32>, it doesn't tell the difference between
1019 95/98/ME/NT/2000/XP/CE/.NET. Use Win32::GetOSName() or
1020 Win32::GetOSVersion() (see L<Win32> and L<perlport>) to distinguish
1021 between the variants.
1025 An internal variable used by PerlIO. A string in two parts, separated
1026 by a C<\0> byte, the first part describes the input layers, the second
1027 part describes the output layers.
1033 The internal variable for debugging support. The meanings of the
1034 various bits are subject to change, but currently indicate:
1040 Debug subroutine enter/exit.
1044 Line-by-line debugging.
1048 Switch off optimizations.
1052 Preserve more data for future interactive inspections.
1056 Keep info about source lines on which a subroutine is defined.
1060 Start with single-step on.
1064 Use subroutine address instead of name when reporting.
1068 Report C<goto &subroutine> as well.
1072 Provide informative "file" names for evals based on the place they were compiled.
1076 Provide informative names to anonymous subroutines based on the place they
1081 Debug assertion subroutines enter/exit.
1085 Some bits may be relevant at compile-time only, some at
1086 run-time only. This is a new mechanism and the details may change.
1088 =item $LAST_REGEXP_CODE_RESULT
1092 The result of evaluation of the last successful C<(?{ code })>
1093 regular expression assertion (see L<perlre>). May be written to.
1095 =item $EXCEPTIONS_BEING_CAUGHT
1099 Current state of the interpreter.
1102 --------- -------------------
1103 undef Parsing module/eval
1104 true (1) Executing an eval
1107 The first state may happen in $SIG{__DIE__} and $SIG{__WARN__} handlers.
1113 The time at which the program began running, in seconds since the
1114 epoch (beginning of 1970). The values returned by the B<-M>, B<-A>,
1115 and B<-C> filetests are based on this value.
1119 Reflects if taint mode is on or off. 1 for on (the program was run with
1120 B<-T>), 0 for off, -1 when only taint warnings are enabled (i.e. with
1121 B<-t> or B<-TU>). This variable is read-only.
1125 Reflects certain Unicode settings of Perl. See L<perlrun>
1126 documentation for the C<-C> switch for more information about
1127 the possible values. This variable is set during Perl startup
1128 and is thereafter read-only.
1134 The revision, version, and subversion of the Perl interpreter, represented
1135 as a string composed of characters with those ordinals. Thus in Perl v5.6.0
1136 it equals C<chr(5) . chr(6) . chr(0)> and will return true for
1137 C<$^V eq v5.6.0>. Note that the characters in this string value can
1138 potentially be in Unicode range.
1140 This can be used to determine whether the Perl interpreter executing a
1141 script is in the right range of versions. (Mnemonic: use ^V for Version
1144 warn "No \"our\" declarations!\n" if $^V and $^V lt v5.6.0;
1146 To convert C<$^V> into its string representation use sprintf()'s
1147 C<"%vd"> conversion:
1149 printf "version is v%vd\n", $^V; # Perl's version
1151 See the documentation of C<use VERSION> and C<require VERSION>
1152 for a convenient way to fail if the running Perl interpreter is too old.
1154 See also C<$]> for an older representation of the Perl version.
1160 The current value of the warning switch, initially true if B<-w>
1161 was used, false otherwise, but directly modifiable. (Mnemonic:
1162 related to the B<-w> switch.) See also L<warnings>.
1164 =item ${^WARNING_BITS}
1166 The current set of warning checks enabled by the C<use warnings> pragma.
1167 See the documentation of C<warnings> for more details.
1169 =item $EXECUTABLE_NAME
1173 The name used to execute the current copy of Perl, from C's
1176 Depending on the host operating system, the value of $^X may be
1177 a relative or absolute pathname of the perl program file, or may
1178 be the string used to invoke perl but not the pathname of the
1179 perl program file. Also, most operating systems permit invoking
1180 programs that are not in the PATH environment variable, so there
1181 is no guarantee that the value of $^X is in PATH. For VMS, the
1182 value may or may not include a version number.
1184 You usually can use the value of $^X to re-invoke an independent
1185 copy of the same perl that is currently running, e.g.,
1187 @first_run = `$^X -le "print int rand 100 for 1..100"`;
1189 But recall that not all operating systems support forking or
1190 capturing of the output of commands, so this complex statement
1191 may not be portable.
1193 It is not safe to use the value of $^X as a path name of a file,
1194 as some operating systems that have a mandatory suffix on
1195 executable files do not require use of the suffix when invoking
1196 a command. To convert the value of $^X to a path name, use the
1197 following statements:
1199 # Build up a set of file names (not command names).
1203 {$this_perl .= $Config{_exe}
1204 unless $this_perl =~ m/$Config{_exe}$/i;}
1206 Because many operating systems permit anyone with read access to
1207 the Perl program file to make a copy of it, patch the copy, and
1208 then execute the copy, the security-conscious Perl programmer
1209 should take care to invoke the installed copy of perl, not the
1210 copy referenced by $^X. The following statements accomplish
1211 this goal, and produce a pathname that can be invoked as a
1212 command or referenced as a file.
1215 $secure_perl_path = $Config{perlpath};
1217 {$secure_perl_path .= $Config{_exe}
1218 unless $secure_perl_path =~ m/$Config{_exe}$/i;}
1222 The special filehandle that iterates over command-line filenames in
1223 C<@ARGV>. Usually written as the null filehandle in the angle operator
1224 C<< <> >>. Note that currently C<ARGV> only has its magical effect
1225 within the C<< <> >> operator; elsewhere it is just a plain filehandle
1226 corresponding to the last file opened by C<< <> >>. In particular,
1227 passing C<\*ARGV> as a parameter to a function that expects a filehandle
1228 may not cause your function to automatically read the contents of all the
1233 contains the name of the current file when reading from <>.
1237 The array @ARGV contains the command-line arguments intended for
1238 the script. C<$#ARGV> is generally the number of arguments minus
1239 one, because C<$ARGV[0]> is the first argument, I<not> the program's
1240 command name itself. See C<$0> for the command name.
1244 The special filehandle that points to the currently open output file
1245 when doing edit-in-place processing with B<-i>. Useful when you have
1246 to do a lot of inserting and don't want to keep modifying $_. See
1247 L<perlrun> for the B<-i> switch.
1251 The array @F contains the fields of each line read in when autosplit
1252 mode is turned on. See L<perlrun> for the B<-a> switch. This array
1253 is package-specific, and must be declared or given a full package name
1254 if not in package main when running under C<strict 'vars'>.
1258 The array @INC contains the list of places that the C<do EXPR>,
1259 C<require>, or C<use> constructs look for their library files. It
1260 initially consists of the arguments to any B<-I> command-line
1261 switches, followed by the default Perl library, probably
1262 F</usr/local/lib/perl>, followed by ".", to represent the current
1263 directory. ("." will not be appended if taint checks are enabled, either by
1264 C<-T> or by C<-t>.) If you need to modify this at runtime, you should use
1265 the C<use lib> pragma to get the machine-dependent library properly
1268 use lib '/mypath/libdir/';
1271 You can also insert hooks into the file inclusion system by putting Perl
1272 code directly into @INC. Those hooks may be subroutine references, array
1273 references or blessed objects. See L<perlfunc/require> for details.
1277 Within a subroutine the array @_ contains the parameters passed to that
1278 subroutine. See L<perlsub>.
1282 The hash %INC contains entries for each filename included via the
1283 C<do>, C<require>, or C<use> operators. The key is the filename
1284 you specified (with module names converted to pathnames), and the
1285 value is the location of the file found. The C<require>
1286 operator uses this hash to determine whether a particular file has
1287 already been included.
1289 If the file was loaded via a hook (e.g. a subroutine reference, see
1290 L<perlfunc/require> for a description of these hooks), this hook is
1291 by default inserted into %INC in place of a filename. Note, however,
1292 that the hook may have set the %INC entry by itself to provide some more
1299 The hash %ENV contains your current environment. Setting a
1300 value in C<ENV> changes the environment for any child processes
1301 you subsequently fork() off.
1307 The hash %SIG contains signal handlers for signals. For example:
1309 sub handler { # 1st argument is signal name
1311 print "Caught a SIG$sig--shutting down\n";
1316 $SIG{'INT'} = \&handler;
1317 $SIG{'QUIT'} = \&handler;
1319 $SIG{'INT'} = 'DEFAULT'; # restore default action
1320 $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
1322 Using a value of C<'IGNORE'> usually has the effect of ignoring the
1323 signal, except for the C<CHLD> signal. See L<perlipc> for more about
1326 Here are some other examples:
1328 $SIG{"PIPE"} = "Plumber"; # assumes main::Plumber (not recommended)
1329 $SIG{"PIPE"} = \&Plumber; # just fine; assume current Plumber
1330 $SIG{"PIPE"} = *Plumber; # somewhat esoteric
1331 $SIG{"PIPE"} = Plumber(); # oops, what did Plumber() return??
1333 Be sure not to use a bareword as the name of a signal handler,
1334 lest you inadvertently call it.
1336 If your system has the sigaction() function then signal handlers are
1337 installed using it. This means you get reliable signal handling.
1339 The default delivery policy of signals changed in Perl 5.8.0 from
1340 immediate (also known as "unsafe") to deferred, also known as
1341 "safe signals". See L<perlipc> for more information.
1343 Certain internal hooks can be also set using the %SIG hash. The
1344 routine indicated by C<$SIG{__WARN__}> is called when a warning message is
1345 about to be printed. The warning message is passed as the first
1346 argument. The presence of a __WARN__ hook causes the ordinary printing
1347 of warnings to STDERR to be suppressed. You can use this to save warnings
1348 in a variable, or turn warnings into fatal errors, like this:
1350 local $SIG{__WARN__} = sub { die $_[0] };
1353 The routine indicated by C<$SIG{__DIE__}> is called when a fatal exception
1354 is about to be thrown. The error message is passed as the first
1355 argument. When a __DIE__ hook routine returns, the exception
1356 processing continues as it would have in the absence of the hook,
1357 unless the hook routine itself exits via a C<goto>, a loop exit, or a die().
1358 The C<__DIE__> handler is explicitly disabled during the call, so that you
1359 can die from a C<__DIE__> handler. Similarly for C<__WARN__>.
1361 Due to an implementation glitch, the C<$SIG{__DIE__}> hook is called
1362 even inside an eval(). Do not use this to rewrite a pending exception
1363 in C<$@>, or as a bizarre substitute for overriding CORE::GLOBAL::die().
1364 This strange action at a distance may be fixed in a future release
1365 so that C<$SIG{__DIE__}> is only called if your program is about
1366 to exit, as was the original intent. Any other use is deprecated.
1368 C<__DIE__>/C<__WARN__> handlers are very special in one respect:
1369 they may be called to report (probable) errors found by the parser.
1370 In such a case the parser may be in inconsistent state, so any
1371 attempt to evaluate Perl code from such a handler will probably
1372 result in a segfault. This means that warnings or errors that
1373 result from parsing Perl should be used with extreme caution, like
1376 require Carp if defined $^S;
1377 Carp::confess("Something wrong") if defined &Carp::confess;
1378 die "Something wrong, but could not load Carp to give backtrace...
1379 To see backtrace try starting Perl with -MCarp switch";
1381 Here the first line will load Carp I<unless> it is the parser who
1382 called the handler. The second line will print backtrace and die if
1383 Carp was available. The third line will be executed only if Carp was
1386 See L<perlfunc/die>, L<perlfunc/warn>, L<perlfunc/eval>, and
1387 L<warnings> for additional information.
1391 =head2 Error Indicators
1393 The variables C<$@>, C<$!>, C<$^E>, and C<$?> contain information
1394 about different types of error conditions that may appear during
1395 execution of a Perl program. The variables are shown ordered by
1396 the "distance" between the subsystem which reported the error and
1397 the Perl process. They correspond to errors detected by the Perl
1398 interpreter, C library, operating system, or an external program,
1401 To illustrate the differences between these variables, consider the
1402 following Perl expression, which uses a single-quoted string:
1405 open my $pipe, "/cdrom/install |" or die $!;
1407 close $pipe or die "bad pipe: $?, $!";
1410 After execution of this statement all 4 variables may have been set.
1412 C<$@> is set if the string to be C<eval>-ed did not compile (this
1413 may happen if C<open> or C<close> were imported with bad prototypes),
1414 or if Perl code executed during evaluation die()d . In these cases
1415 the value of $@ is the compile error, or the argument to C<die>
1416 (which will interpolate C<$!> and C<$?>!). (See also L<Fatal>,
1419 When the eval() expression above is executed, open(), C<< <PIPE> >>,
1420 and C<close> are translated to calls in the C run-time library and
1421 thence to the operating system kernel. C<$!> is set to the C library's
1422 C<errno> if one of these calls fails.
1424 Under a few operating systems, C<$^E> may contain a more verbose
1425 error indicator, such as in this case, "CDROM tray not closed."
1426 Systems that do not support extended error messages leave C<$^E>
1429 Finally, C<$?> may be set to non-0 value if the external program
1430 F</cdrom/install> fails. The upper eight bits reflect specific
1431 error conditions encountered by the program (the program's exit()
1432 value). The lower eight bits reflect mode of failure, like signal
1433 death and core dump information See wait(2) for details. In
1434 contrast to C<$!> and C<$^E>, which are set only if error condition
1435 is detected, the variable C<$?> is set on each C<wait> or pipe
1436 C<close>, overwriting the old value. This is more like C<$@>, which
1437 on every eval() is always set on failure and cleared on success.
1439 For more details, see the individual descriptions at C<$@>, C<$!>, C<$^E>,
1442 =head2 Technical Note on the Syntax of Variable Names
1444 Variable names in Perl can have several formats. Usually, they
1445 must begin with a letter or underscore, in which case they can be
1446 arbitrarily long (up to an internal limit of 251 characters) and
1447 may contain letters, digits, underscores, or the special sequence
1448 C<::> or C<'>. In this case, the part before the last C<::> or
1449 C<'> is taken to be a I<package qualifier>; see L<perlmod>.
1451 Perl variable names may also be a sequence of digits or a single
1452 punctuation or control character. These names are all reserved for
1453 special uses by Perl; for example, the all-digits names are used
1454 to hold data captured by backreferences after a regular expression
1455 match. Perl has a special syntax for the single-control-character
1456 names: It understands C<^X> (caret C<X>) to mean the control-C<X>
1457 character. For example, the notation C<$^W> (dollar-sign caret
1458 C<W>) is the scalar variable whose name is the single character
1459 control-C<W>. This is better than typing a literal control-C<W>
1462 Finally, new in Perl 5.6, Perl variable names may be alphanumeric
1463 strings that begin with control characters (or better yet, a caret).
1464 These variables must be written in the form C<${^Foo}>; the braces
1465 are not optional. C<${^Foo}> denotes the scalar variable whose
1466 name is a control-C<F> followed by two C<o>'s. These variables are
1467 reserved for future special uses by Perl, except for the ones that
1468 begin with C<^_> (control-underscore or caret-underscore). No
1469 control-character name that begins with C<^_> will acquire a special
1470 meaning in any future version of Perl; such names may therefore be
1471 used safely in programs. C<$^_> itself, however, I<is> reserved.
1473 Perl identifiers that begin with digits, control characters, or
1474 punctuation characters are exempt from the effects of the C<package>
1475 declaration and are always forced to be in package C<main>; they are
1476 also exempt from C<strict 'vars'> errors. A few other names are also
1477 exempt in these ways:
1485 In particular, the new special C<${^_XYZ}> variables are always taken
1486 to be in package C<main>, regardless of any C<package> declarations
1491 Due to an unfortunate accident of Perl's implementation, C<use
1492 English> imposes a considerable performance penalty on all regular
1493 expression matches in a program, regardless of whether they occur
1494 in the scope of C<use English>. For that reason, saying C<use
1495 English> in libraries is strongly discouraged. See the
1496 Devel::SawAmpersand module documentation from CPAN
1497 ( http://www.cpan.org/modules/by-module/Devel/ )
1498 for more information.
1500 Having to even think about the C<$^S> variable in your exception
1501 handlers is simply wrong. C<$SIG{__DIE__}> as currently implemented
1502 invites grievous and difficult to track down errors. Avoid it
1503 and use an C<END{}> or CORE::GLOBAL::die override instead.