📄 perlvar.pod
字号:
=head1 NAMEperlvar - Perl predefined variables=head1 DESCRIPTION=head2 Predefined NamesThe following names have special meaning to Perl. Most punctuation names have reasonable mnemonics, or analogs in theshells. Nevertheless, if you wish to use long variable names,you need only say use English;at the top of your program. This will alias all the short names to thelong names in the current package. Some even have medium names,generally borrowed from B<awk>.If you don't mind the performance hit, variables that depend on thecurrently selected filehandle may instead be set by calling anappropriate object method on the IO::Handle object. (Summary linesbelow for this contain the word HANDLE.) First you must say use IO::Handle;after which you may use either method HANDLE EXPRor more safely, HANDLE->method(EXPR)Each method returns the old value of the IO::Handle attribute.The methods each take an optional EXPR, which if supplied specifies thenew value for the IO::Handle attribute in question. If not supplied,most methods do nothing to the current value--except forautoflush(), which will assume a 1 for you, just to be different.Because loading in the IO::Handle class is an expensive operation, you shouldlearn how to use the regular built-in variables.A few of these variables are considered "read-only". This means that ifyou try to assign to this variable, either directly or indirectly througha reference, you'll raise a run-time exception.The following list is ordered by scalar variables first, then thearrays, then the hashes.=over 8=item $ARG=item $_The default input and pattern-searching space. The following pairs areequivalent: while (<>) {...} # equivalent only in while! while (defined($_ = <>)) {...} /^Subject:/ $_ =~ /^Subject:/ tr/a-z/A-Z/ $_ =~ tr/a-z/A-Z/ chomp chomp($_)Here are the places where Perl will assume $_ even if youdon't use it:=over 3=item *Various unary functions, including functions like ord() and int(), as wellas the all file tests (C<-f>, C<-d>) except for C<-t>, which defaults toSTDIN.=item *Various list functions like print() and unlink().=item *The pattern matching operations C<m//>, C<s///>, and C<tr///> when usedwithout an C<=~> operator.=item *The default iterator variable in a C<foreach> loop if no othervariable is supplied.=item *The implicit iterator variable in the grep() and map() functions.=item *The default place to put an input record when a C<< <FH> >>operation's result is tested by itself as the sole criterion of a C<while>test. Outside a C<while> test, this will not happen.=back(Mnemonic: underline is understood in certain operations.)=back=over 8=item $<I<digits>>Contains the subpattern from the corresponding set of capturingparentheses from the last pattern match, not counting patternsmatched in nested blocks that have been exited already. (Mnemonic:like \digits.) These variables are all read-only and dynamicallyscoped to the current BLOCK.=item $MATCH=item $&The string matched by the last successful pattern match (not countingany matches hidden within a BLOCK or eval() enclosed by the currentBLOCK). (Mnemonic: like & in some editors.) This variable is read-onlyand dynamically scoped to the current BLOCK.The use of this variable anywhere in a program imposes a considerableperformance penalty on all regular expression matches. See L<BUGS>.=item $PREMATCH=item $`The string preceding whatever was matched by the last successfulpattern match (not counting any matches hidden within a BLOCK or evalenclosed by the current BLOCK). (Mnemonic: C<`> often precedes a quotedstring.) This variable is read-only.The use of this variable anywhere in a program imposes a considerableperformance penalty on all regular expression matches. See L<BUGS>.=item $POSTMATCH=item $'The string following whatever was matched by the last successfulpattern match (not counting any matches hidden within a BLOCK or eval()enclosed by the current BLOCK). (Mnemonic: C<'> often follows a quotedstring.) Example: $_ = 'abcdefghi'; /def/; print "$`:$&:$'\n"; # prints abc:def:ghiThis variable is read-only and dynamically scoped to the current BLOCK.The use of this variable anywhere in a program imposes a considerableperformance penalty on all regular expression matches. See L<BUGS>.=item $LAST_PAREN_MATCH=item $+The last bracket matched by the last search pattern. This is useful ifyou don't know which one of a set of alternative patterns matched. Forexample: /Version: (.*)|Revision: (.*)/ && ($rev = $+);(Mnemonic: be positive and forward looking.)This variable is read-only and dynamically scoped to the current BLOCK.=item @LAST_MATCH_END=item @+This array holds the offsets of the ends of the last successfulsubmatches in the currently active dynamic scope. C<$+[0]> isthe offset into the string of the end of the entire match. Thisis the same value as what the C<pos> function returns when calledon the variable that was matched against. The I<n>th elementof this array holds the offset of the I<n>th submatch, soC<$+[1]> is the offset past where $1 ends, C<$+[2]> the offsetpast where $2 ends, and so on. You can use C<$#+> to determinehow many subgroups were in the last successful match. See theexamples given for the C<@-> variable.=item $MULTILINE_MATCHING=item $*Set to a non-zero integer value to do multi-line matching within astring, 0 (or undefined) to tell Perl that it can assume that stringscontain a single line, for the purpose of optimizing pattern matches.Pattern matches on strings containing multiple newlines can produceconfusing results when C<$*> is 0 or undefined. Default is undefined.(Mnemonic: * matches multiple things.) This variable influences theinterpretation of only C<^> and C<$>. A literal newline can be searchedfor even when C<$* == 0>.Use of C<$*> is deprecated in modern Perl, supplanted by the C</s> and C</m> modifiers on pattern matching.Assigning a non-numerical value to C<$*> triggers a warning (and makesC<$*> act if C<$* == 0>), while assigning a numerical value to C<$*>makes that an implicit C<int> is applied on the value.=item input_line_number HANDLE EXPR=item $INPUT_LINE_NUMBER=item $NR=item $.The current input record number for the last file handle from whichyou just read() (or called a C<seek> or C<tell> on). The valuemay be different from the actual physical line number in the file,depending on what notion of "line" is in effect--see C<$/> on howto change that. An explicit close on a filehandle resets the linenumber. Because C<< <> >> never does an explicit close, linenumbers increase across ARGV files (but see examples in L<perlfunc/eof>).Consider this variable read-only: setting it does not repositionthe seek pointer; you'll have to do that on your own. Localizing C<$.>has the effect of also localizing Perl's notion of "the last readfilehandle". (Mnemonic: many programs use "." to mean the current linenumber.)=item input_record_separator HANDLE EXPR=item $INPUT_RECORD_SEPARATOR=item $RS=item $/The input record separator, newline by default. This influences Perl's idea of what a "line" is. Works like B<awk>'s RSvariable, including treating empty lines as a terminator if set tothe null string. (An empty line cannot contain any spacesor tabs.) You may set it to a multi-character string to match amulti-character terminator, or to C<undef> to read through the endof file. Setting it to C<"\n\n"> means something slightlydifferent than setting to C<"">, if the file contains consecutiveempty lines. Setting to C<""> will treat two or more consecutiveempty lines as a single empty line. Setting to C<"\n\n"> willblindly assume that the next input character belongs to the nextparagraph, even if it's a newline. (Mnemonic: / delimitsline boundaries when quoting poetry.) undef $/; # enable "slurp" mode $_ = <FH>; # whole file now here s/\n[ \t]+/ /g;Remember: the value of C<$/> is a string, not a regex. B<awk> has to bebetter for something. :-)Setting C<$/> to a reference to an integer, scalar containing an integer, orscalar that's convertible to an integer will attempt to read recordsinstead of lines, with the maximum record size being the referencedinteger. So this: $/ = \32768; # or \"32768", or \$var_containing_32768 open(FILE, $myfile); $_ = <FILE>;will read a record of no more than 32768 bytes from FILE. If you'renot reading from a record-oriented file (or your OS doesn't haverecord-oriented files), then you'll likely get a full chunk of datawith every read. If a record is larger than the record size you'veset, you'll get the record back in pieces.On VMS, record reads are done with the equivalent of C<sysread>,so it's best not to mix record and non-record reads on the samefile. (This is unlikely to be a problem, because any file you'dwant to read in record mode is probably unusable in line mode.)Non-VMS systems do normal I/O, so it's safe to mix record andnon-record reads of a file.See also L<perlport/"Newlines">. Also see C<$.>.=item autoflush HANDLE EXPR=item $OUTPUT_AUTOFLUSH=item $|If set to nonzero, forces a flush right away and after every writeor print on the currently selected output channel. Default is 0(regardless of whether the channel is really buffered by thesystem or not; C<$|> tells you only whether you've asked Perlexplicitly to flush after each write). STDOUT willtypically be line buffered if output is to the terminal and blockbuffered otherwise. Setting this variable is useful primarily whenyou are outputting to a pipe or socket, such as when you are runninga Perl program under B<rsh> and want to see the output as it'shappening. This has no effect on input buffering. See L<perlfunc/getc>for that. (Mnemonic: when you want your pipes to be piping hot.)=item output_field_separator HANDLE EXPR=item $OUTPUT_FIELD_SEPARATOR=item $OFS=item $,The output field separator for the print operator. Ordinarily theprint operator simply prints out its arguments without furtheradornment. To get behavior more like B<awk>, set this variable asyou would set B<awk>'s OFS variable to specify what is printedbetween fields. (Mnemonic: what is printed when there is a "," inyour print statement.)=item output_record_separator HANDLE EXPR=item $OUTPUT_RECORD_SEPARATOR=item $ORS=item $\The output record separator for the print operator. Ordinarily theprint operator simply prints out its arguments as is, with notrailing newline or other end-of-record string added. To getbehavior more like B<awk>, set this variable as you would setB<awk>'s ORS variable to specify what is printed at the end of theprint. (Mnemonic: you set C<$\> instead of adding "\n" at theend of the print. Also, it's just like C<$/>, but it's what youget "back" from Perl.)=item $LIST_SEPARATOR=item $"This is like C<$,> except that it applies to array and slice valuesinterpolated into a double-quoted string (or similar interpretedstring). Default is a space. (Mnemonic: obvious, I think.)=item $SUBSCRIPT_SEPARATOR=item $SUBSEP=item $;The subscript separator for multidimensional array emulation. If yourefer to a hash element as $foo{$a,$b,$c}it really means $foo{join($;, $a, $b, $c)}But don't put @foo{$a,$b,$c} # a slice--note the @which means ($foo{$a},$foo{$b},$foo{$c})Default is "\034", the same as SUBSEP in B<awk>. If yourkeys contain binary data there might not be any safe value for C<$;>.(Mnemonic: comma (the syntactic subscript separator) is asemi-semicolon. Yeah, I know, it's pretty lame, but C<$,> is alreadytaken for something more important.)Consider using "real" multidimensional arrays as describedin L<perllol>.=item $OFMT=item $#The output format for printed numbers. This variable is a half-heartedattempt to emulate B<awk>'s OFMT variable. There are times, however,when B<awk> and Perl have differing notions of what counts as numeric. The initial value is "%.I<n>g", where I<n> is the valueof the macro DBL_DIG from your system's F<float.h>. This is different fromB<awk>'s default OFMT setting of "%.6g", so you need to set C<$#>explicitly to get B<awk>'s value. (Mnemonic: # is the number sign.)Use of C<$#> is deprecated.=item format_page_number HANDLE EXPR=item $FORMAT_PAGE_NUMBER=item $%The current page number of the currently selected output channel.Used with formats.(Mnemonic: % is page number in B<nroff>.)=item format_lines_per_page HANDLE EXPR=item $FORMAT_LINES_PER_PAGE=item $=The current page length (printable lines) of the currently selectedoutput channel. Default is 60. Used with formats.(Mnemonic: = has horizontal lines.)=item format_lines_left HANDLE EXPR
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -