perlop.pod
来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 1,675 行 · 第 1/5 页
POD
1,675 行
Using this operator can lead to programs that are difficult to port,
because the shell commands called vary between systems, and may in
fact not be present at all. As one example, the C<type> command under
the POSIX shell is very different from the C<type> command under DOS.
That doesn't mean you should go out of your way to avoid backticks
when they're the right way to get something done. Perl was made to be
a glue language, and one of the things it glues together is commands.
Just understand what you're getting yourself into.
See L<"I/O Operators"> for more discussion.
=item qw/STRING/
Returns a list of the words extracted out of STRING, using embedded
whitespace as the word delimiters. It is exactly equivalent to
split(' ', q/STRING/);
This equivalency means that if used in scalar context, you'll get split's
(unfortunate) scalar context behavior, complete with mysterious warnings.
Some frequently seen examples:
use POSIX qw( setlocale localeconv )
@EXPORT = qw( foo bar baz );
A common mistake is to try to separate the words with comma or to put
comments into a multi-line C<qw>-string. For this reason the C<-w>
switch produce warnings if the STRING contains the "," or the "#"
character.
=item s/PATTERN/REPLACEMENT/egimosx
Searches a string for a pattern, and if found, replaces that pattern
with the replacement text and returns the number of substitutions
made. Otherwise it returns false (specifically, the empty string).
If no string is specified via the C<=~> or C<!~> operator, the C<$_>
variable is searched and modified. (The string specified with C<=~> must
be scalar variable, an array element, a hash element, or an assignment
to one of those, i.e., an lvalue.)
If the delimiter chosen is single quote, no variable interpolation is
done on either the PATTERN or the REPLACEMENT. Otherwise, if the
PATTERN contains a $ that looks like a variable rather than an
end-of-string test, the variable will be interpolated into the pattern
at run-time. If you want the pattern compiled only once the first time
the variable is interpolated, use the C</o> option. If the pattern
evaluates to the empty string, the last successfully executed regular
expression is used instead. See L<perlre> for further explanation on these.
See L<perllocale> for discussion of additional considerations that apply
when C<use locale> is in effect.
Options are:
e Evaluate the right side as an expression.
g Replace globally, i.e., all occurrences.
i Do case-insensitive pattern matching.
m Treat string as multiple lines.
o Compile pattern only once.
s Treat string as single line.
x Use extended regular expressions.
Any non-alphanumeric, non-whitespace delimiter may replace the
slashes. If single quotes are used, no interpretation is done on the
replacement string (the C</e> modifier overrides this, however). Unlike
Perl 4, Perl 5 treats backticks as normal delimiters; the replacement
text is not evaluated as a command. If the
PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own
pair of quotes, which may or may not be bracketing quotes, e.g.,
C<s(foo)(bar)> or C<sE<lt>fooE<gt>/bar/>. A C</e> will cause the
replacement portion to be interpreted as a full-fledged Perl expression
and eval()ed right then and there. It is, however, syntax checked at
compile-time.
Examples:
s/\bgreen\b/mauve/g; # don't change wintergreen
$path =~ s|/usr/bin|/usr/local/bin|;
s/Login: $foo/Login: $bar/; # run-time pattern
($foo = $bar) =~ s/this/that/; # copy first, then change
$count = ($paragraph =~ s/Mister\b/Mr./g); # get change-count
$_ = 'abc123xyz';
s/\d+/$&*2/e; # yields 'abc246xyz'
s/\d+/sprintf("%5d",$&)/e; # yields 'abc 246xyz'
s/\w/$& x 2/eg; # yields 'aabbcc 224466xxyyzz'
s/%(.)/$percent{$1}/g; # change percent escapes; no /e
s/%(.)/$percent{$1} || $&/ge; # expr now, so /e
s/^=(\w+)/&pod($1)/ge; # use function call
# expand variables in $_, but dynamics only, using
# symbolic dereferencing
s/\$(\w+)/${$1}/g;
# /e's can even nest; this will expand
# any embedded scalar variable (including lexicals) in $_
s/(\$\w+)/$1/eeg;
# Delete (most) C comments.
$program =~ s {
/\* # Match the opening delimiter.
.*? # Match a minimal number of characters.
\*/ # Match the closing delimiter.
} []gsx;
s/^\s*(.*?)\s*$/$1/; # trim white space in $_, expensively
for ($variable) { # trim white space in $variable, cheap
s/^\s+//;
s/\s+$//;
}
s/([^ ]*) *([^ ]*)/$2 $1/; # reverse 1st two fields
Note the use of $ instead of \ in the last example. Unlike
B<sed>, we use the \E<lt>I<digit>E<gt> form in only the left hand side.
Anywhere else it's $E<lt>I<digit>E<gt>.
Occasionally, you can't use just a C</g> to get all the changes
to occur. Here are two common cases:
# put commas in the right places in an integer
1 while s/(.*\d)(\d\d\d)/$1,$2/g; # perl4
1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g; # perl5
# expand tabs to 8-column spacing
1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
=item tr/SEARCHLIST/REPLACEMENTLIST/cds
=item y/SEARCHLIST/REPLACEMENTLIST/cds
Transliterates all occurrences of the characters found in the search list
with the corresponding character in the replacement list. It returns
the number of characters replaced or deleted. If no string is
specified via the =~ or !~ operator, the $_ string is transliterated. (The
string specified with =~ must be a scalar variable, an array element, a
hash element, or an assignment to one of those, i.e., an lvalue.)
A character range may be specified with a hyphen, so C<tr/A-J/0-9/>
does the same replacement as C<tr/ACEGIBDFHJ/0246813579/>.
For B<sed> devotees, C<y> is provided as a synonym for C<tr>. If the
SEARCHLIST is delimited by bracketing quotes, the REPLACEMENTLIST has
its own pair of quotes, which may or may not be bracketing quotes,
e.g., C<tr[A-Z][a-z]> or C<tr(+\-*/)/ABCD/>.
Options:
c Complement the SEARCHLIST.
d Delete found but unreplaced characters.
s Squash duplicate replaced characters.
If the C</c> modifier is specified, the SEARCHLIST character set is
complemented. If the C</d> modifier is specified, any characters specified
by SEARCHLIST not found in REPLACEMENTLIST are deleted. (Note
that this is slightly more flexible than the behavior of some B<tr>
programs, which delete anything they find in the SEARCHLIST, period.)
If the C</s> modifier is specified, sequences of characters that were
transliterated to the same character are squashed down to a single instance of the
character.
If the C</d> modifier is used, the REPLACEMENTLIST is always interpreted
exactly as specified. Otherwise, if the REPLACEMENTLIST is shorter
than the SEARCHLIST, the final character is replicated till it is long
enough. If the REPLACEMENTLIST is empty, the SEARCHLIST is replicated.
This latter is useful for counting characters in a class or for
squashing character sequences in a class.
Examples:
$ARGV[1] =~ tr/A-Z/a-z/; # canonicalize to lower case
$cnt = tr/*/*/; # count the stars in $_
$cnt = $sky =~ tr/*/*/; # count the stars in $sky
$cnt = tr/0-9//; # count the digits in $_
tr/a-zA-Z//s; # bookkeeper -> bokeper
($HOST = $host) =~ tr/a-z/A-Z/;
tr/a-zA-Z/ /cs; # change non-alphas to single space
tr [\200-\377]
[\000-\177]; # delete 8th bit
If multiple transliterations are given for a character, only the first one is used:
tr/AAA/XYZ/
will transliterate any A to X.
Note that because the transliteration table is built at compile time, neither
the SEARCHLIST nor the REPLACEMENTLIST are subjected to double quote
interpolation. That means that if you want to use variables, you must use
an eval():
eval "tr/$oldlist/$newlist/";
die $@ if $@;
eval "tr/$oldlist/$newlist/, 1" or die $@;
=back
=head2 Gory details of parsing quoted constructs
When presented with something which may have several different
interpretations, Perl uses the principle B<DWIM> (expanded to Do What I Mean
- not what I wrote) to pick up the most probable interpretation of the
source. This strategy is so successful that Perl users usually do not
suspect ambivalence of what they write. However, time to time Perl's ideas
differ from what the author meant.
The target of this section is to clarify the Perl's way of interpreting
quoted constructs. The most frequent reason one may have to want to know the
details discussed in this section is hairy regular expressions. However, the
first steps of parsing are the same for all Perl quoting operators, so here
they are discussed together.
Some of the passes discussed below are performed concurrently, but as
far as results are the same, we consider them one-by-one. For different
quoting constructs Perl performs different number of passes, from
one to five, but they are always performed in the same order.
=over
=item Finding the end
First pass is finding the end of the quoted construct, be it multichar ender
C<"\nEOF\n"> of C<<<EOF> construct, C</> which terminates C<qq/> construct,
C<]> which terminates C<qq[> construct, or C<E<gt>> which terminates a
fileglob started with C<<>.
When searching for multichar construct no skipping is performed. When
searching for one-char non-matching delimiter, such as C</>, combinations
C<\\> and C<\/> are skipped. When searching for one-char matching delimiter,
such as C<]>, combinations C<\\>, C<\]> and C<\[> are skipped, and
nested C<[>, C<]> are skipped as well.
For 3-parts constructs, C<s///> etc. the search is repeated once more.
During this search no attention is paid to the semantic of the construct, thus
"$hash{"$foo/$bar"}"
or
m/
bar # This is not a comment, this slash / terminated m//!
/x
do not form legal quoted expressions. Note that since the slash which
terminated C<m//> was followed by a C<SPACE>, this is not C<m//x>,
thus C<#> was interpreted as a literal C<#>.
=item Removal of backslashes before delimiters
During the second pass the text between the starting delimiter and
the ending delimiter is copied to a safe location, and the C<\> is
removed from combinations consisting of C<\> and delimiter(s) (both starting
and ending delimiter if they differ).
The removal does not happen for multi-char delimiters.
Note that the combination C<\\> is left as it was!
Starting from this step no information about the delimiter(s) is used in the
parsing.
=item Interpolation
Next step is interpolation in the obtained delimiter-independent text.
There are four different cases.
=over
=item C<<<'EOF'>, C<m''>, C<s'''>, C<tr///>, C<y///>
No interpolation is performed.
=item C<''>, C<q//>
The only interpolation is removal of C<\> from pairs C<\\>.
=item C<"">, C<``>, C<qq//>, C<qx//>, C<<file*globE<gt>>
C<\Q>, C<\U>, C<\u>, C<\L>, C<\l> (possibly paired with C<\E>) are converted
to corresponding Perl constructs, thus C<"$foo\Qbaz$bar"> is converted to
$foo . (quotemeta("baz" . $bar));
Other combinations of C<\> with following chars are substituted with
appropriate expansions.
Interpolated scalars and arrays are converted to C<join> and C<.> Perl
constructs, thus C<"'@arr'"> becomes
"'" . (join $", @arr) . "'";
Since all three above steps are performed simultaneously left-to-right,
the is no way to insert a literal C<$> or C<@> inside C<\Q\E> pair: it
cannot be protected by C<\>, since any C<\> (except in C<\E>) is
interpreted as a literal inside C<\Q\E>, and any C<$> is
interpreted as starting an interpolated scalar.
Note also that the interpolating code needs to make decision where the
interpolated scalar ends, say, whether C<"a $b -E<gt> {c}"> means
"a " . $b . " -> {c}";
or
"a " . $b -> {c};
Most the time the decision is to take the longest possible text which does
not include spaces between components and contains matching braces/brackets.
=item C<?RE?>, C</RE/>, C<m/RE/>, C<s/RE/foo/>,
Processing of C<\Q>, C<\U>, C<\u>, C<\L>, C<\l> and interpolation happens
(almost) as with C<qq//> constructs, but I<the substitution of C<\> followed by
other chars is not performed>! Moreover, inside C<(?{BLOCK})> no processing
is performed at all.
Interpolation has several quirks: C<$|>, C<$(> and C<$)> are not interpolated, and
constructs C<$var[SOMETHING]> are I<voted> (by several different estimators)
to be an array element or C<$var> followed by a RE alternative. This is
the place where the notation C<${arr[$bar]}> comes handy: C</${arr[0-9]}/>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?