perlop.pod

来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 1,675 行 · 第 1/5 页

POD
1,675 行
字号
and prefer a CR+LF (C<"\012\015"> or C<"\cJ\cM">) for line terminators,
and although they often accept just C<"\012">, they seldom tolerate just
C<"\015">.  If you get in the habit of using C<"\n"> for networking,
you may be burned some day.

You cannot include a literal C<$> or C<@> within a C<\Q> sequence. 
An unescaped C<$> or C<@> interpolates the corresponding variable, 
while escaping will cause the literal string C<\$> to be inserted.
You'll need to write something like C<m/\Quser\E\@\Qhost/>. 

Patterns are subject to an additional level of interpretation as a
regular expression.  This is done as a second pass, after variables are
interpolated, so that regular expressions may be incorporated into the
pattern from the variables.  If this is not what you want, use C<\Q> to
interpolate a variable literally.

Apart from the above, there are no multiple levels of interpolation.  In
particular, contrary to the expectations of shell programmers, back-quotes
do I<NOT> interpolate within double quotes, nor do single quotes impede
evaluation of variables when used within double quotes.

=head2 Regexp Quote-Like Operators

Here are the quote-like operators that apply to pattern
matching and related activities.

Most of this section is related to use of regular expressions from Perl.
Such a use may be considered from two points of view: Perl handles a
a string and a "pattern" to RE (regular expression) engine to match, 
RE engine finds (or does not find) the match, and Perl uses the findings 
of RE engine for its operation, possibly asking the engine for other matches.

RE engine has no idea what Perl is going to do with what it finds, 
similarly, the rest of Perl has no idea what a particular regular expression 
means to RE engine.  This creates a clean separation, and in this section
we discuss matching from Perl point of view only.  The other point of
view may be found in L<perlre>.

=over 8

=item ?PATTERN?

This is just like the C</pattern/> search, except that it matches only
once between calls to the reset() operator.  This is a useful
optimization when you want to see only the first occurrence of
something in each file of a set of files, for instance.  Only C<??>
patterns local to the current package are reset.

    while (<>) {
	if (?^$?) {
			    # blank line between header and body
	}
    } continue {
	reset if eof;	    # clear ?? status for next file
    }

This usage is vaguely deprecated, and may be removed in some future
version of Perl.

=item m/PATTERN/cgimosx

=item /PATTERN/cgimosx

Searches a string for a pattern match, and in scalar context returns
true (1) or false ('').  If no string is specified via the C<=~> or
C<!~> operator, the $_ string is searched.  (The string specified with
C<=~> need not be an lvalue--it may be the result of an expression
evaluation, but remember the C<=~> binds rather tightly.)  See also
L<perlre>.
See L<perllocale> for discussion of additional considerations that apply
when C<use locale> is in effect.

Options are:

    c	Do not reset search position on a failed match when /g is in effect.
    g	Match globally, i.e., find 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.

If "/" is the delimiter then the initial C<m> is optional.  With the C<m>
you can use any pair of non-alphanumeric, non-whitespace characters 
as delimiters (if single quotes are used, no interpretation is done
on the replacement string. Unlike Perl 4, Perl 5 treats backticks as normal
delimiters; the replacement text is not evaluated as a command).
This is particularly useful for matching Unix path names
that contain "/", to avoid LTS (leaning toothpick syndrome).  If "?" is
the delimiter, then the match-only-once rule of C<?PATTERN?> applies.

PATTERN may contain variables, which will be interpolated (and the
pattern recompiled) every time the pattern search is evaluated.  (Note
that C<$)> and C<$|> might not be interpolated because they look like
end-of-string tests.)  If you want such a pattern to be compiled only
once, add a C</o> after the trailing delimiter.  This avoids expensive
run-time recompilations, and is useful when the value you are
interpolating won't change over the life of the script.  However, mentioning
C</o> constitutes a promise that you won't change the variables in the pattern.
If you change them, Perl won't even notice.

If the PATTERN evaluates to the empty string, the last
I<successfully> matched regular expression is used instead.

If the C</g> option is not used, C<m//> in a list context returns a
list consisting of the subexpressions matched by the parentheses in the
pattern, i.e., (C<$1>, C<$2>, C<$3>...).  (Note that here C<$1> etc. are
also set, and that this differs from Perl 4's behavior.)  When there are
no parentheses in the pattern, the return value is the list C<(1)> for
success.  With or without parentheses, an empty list is returned upon
failure.

Examples:

    open(TTY, '/dev/tty');
    <TTY> =~ /^y/i && foo();	# do foo if desired

    if (/Version: *([0-9.]*)/) { $version = $1; }

    next if m#^/usr/spool/uucp#;

    # poor man's grep
    $arg = shift;
    while (<>) {
	print if /$arg/o;	# compile only once
    }

    if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))

This last example splits $foo into the first two words and the
remainder of the line, and assigns those three fields to $F1, $F2, and
$Etc.  The conditional is true if any variables were assigned, i.e., if
the pattern matched.

The C</g> modifier specifies global pattern matching--that is, matching
as many times as possible within the string.  How it behaves depends on
the context.  In list context, it returns a list of all the
substrings matched by all the parentheses in the regular expression.
If there are no parentheses, it returns a list of all the matched
strings, as if there were parentheses around the whole pattern.

In scalar context, each execution of C<m//g> finds the next match,
returning TRUE if it matches, and FALSE if there is no further match.
The position after the last match can be read or set using the pos()
function; see L<perlfunc/pos>.   A failed match normally resets the
search position to the beginning of the string, but you can avoid that
by adding the C</c> modifier (e.g. C<m//gc>).  Modifying the target
string also resets the search position.

You can intermix C<m//g> matches with C<m/\G.../g>, where C<\G> is a
zero-width assertion that matches the exact position where the previous
C<m//g>, if any, left off.  The C<\G> assertion is not supported without
the C</g> modifier; currently, without C</g>, C<\G> behaves just like
C<\A>, but that's accidental and may change in the future.

Examples:

    # list context
    ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);

    # scalar context
    $/ = ""; $* = 1;  # $* deprecated in modern perls
    while (defined($paragraph = <>)) {
	while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
	    $sentences++;
	}
    }
    print "$sentences\n";

    # using m//gc with \G
    $_ = "ppooqppqq";
    while ($i++ < 2) {
        print "1: '";
        print $1 while /(o)/gc; print "', pos=", pos, "\n";
        print "2: '";
        print $1 if /\G(q)/gc;  print "', pos=", pos, "\n";
        print "3: '";
        print $1 while /(p)/gc; print "', pos=", pos, "\n";
    }

The last example should print:

    1: 'oo', pos=4
    2: 'q', pos=5
    3: 'pp', pos=7
    1: '', pos=7
    2: 'q', pos=8
    3: '', pos=8

A useful idiom for C<lex>-like scanners is C</\G.../gc>.  You can
combine several regexps like this to process a string part-by-part,
doing different actions depending on which regexp matched.  Each
regexp tries to match where the previous one leaves off.

 $_ = <<'EOL';
      $url = new URI::URL "http://www/";   die if $url eq "xXx";
 EOL
 LOOP:
    {
      print(" digits"),		redo LOOP if /\G\d+\b[,.;]?\s*/gc;
      print(" lowercase"),	redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
      print(" UPPERCASE"),	redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
      print(" Capitalized"),	redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
      print(" MiXeD"),		redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
      print(" alphanumeric"),	redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
      print(" line-noise"),	redo LOOP if /\G[^A-Za-z0-9]+/gc;
      print ". That's all!\n";
    }

Here is the output (split into several lines):

 line-noise lowercase line-noise lowercase UPPERCASE line-noise
 UPPERCASE line-noise lowercase line-noise lowercase line-noise
 lowercase lowercase line-noise lowercase lowercase line-noise
 MiXeD line-noise. That's all!

=item q/STRING/

=item C<'STRING'>

A single-quoted, literal string. A backslash represents a backslash
unless followed by the delimiter or another backslash, in which case
the delimiter or backslash is interpolated.

    $foo = q!I said, "You said, 'She said it.'"!;
    $bar = q('This is it.');
    $baz = '\n';		# a two-character string

=item qq/STRING/

=item "STRING"

A double-quoted, interpolated string.

    $_ .= qq
     (*** The previous line contains the naughty word "$1".\n)
		if /(tcl|rexx|python)/;      # :-)
    $baz = "\n";		# a one-character string

=item qr/STRING/imosx

A string which is (possibly) interpolated and then compiled as a
regular expression. The result may be used as a pattern in a match

    $re = qr/$pattern/;
    $string =~ /foo${re}bar/;	# can be interpolated in other patterns
    $string =~ $re;		# or used standalone

Options are:

    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.

The benefit from this is that the pattern is precompiled into an internal
representation, and does not need to be recompiled every time a match
is attempted.  This makes it very efficient to do something like:

    foreach $pattern (@pattern_list) {
	my $re = qr/$pattern/;
	foreach $line (@lines) {
	    if($line =~ /$re/) {
		do_something($line);
	    }
	}
    }

See L<perlre> for additional information on valid syntax for STRING, and
for a detailed look at the semantics of regular expressions.

=item qx/STRING/

=item `STRING`

A string which is (possibly) interpolated and then executed as a system
command with C</bin/sh> or its equivalent.  Shell wildcards, pipes,
and redirections will be honored.  The collected standard output of the
command is returned; standard error is unaffected.  In scalar context,
it comes back as a single (potentially multi-line) string.  In list
context, returns a list of lines (however you've defined lines with $/
or $INPUT_RECORD_SEPARATOR).

Because backticks do not affect standard error, use shell file descriptor
syntax (assuming the shell supports this) if you care to address this.
To capture a command's STDERR and STDOUT together:

    $output = `cmd 2>&1`;

To capture a command's STDOUT but discard its STDERR:

    $output = `cmd 2>/dev/null`;

To capture a command's STDERR but discard its STDOUT (ordering is
important here):

    $output = `cmd 2>&1 1>/dev/null`;

To exchange a command's STDOUT and STDERR in order to capture the STDERR
but leave its STDOUT to come out the old STDERR:

    $output = `cmd 3>&1 1>&2 2>&3 3>&-`;

To read both a command's STDOUT and its STDERR separately, it's easiest
and safest to redirect them separately to files, and then read from those
files when the program is done:

    system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");

Using single-quote as a delimiter protects the command from Perl's
double-quote interpolation, passing it on to the shell instead:

    $perl_info  = qx(ps $$);            # that's Perl's $$
    $shell_info = qx'ps $$';            # that's the new shell's $$

Note that how the string gets evaluated is entirely subject to the command
interpreter on your system.  On most platforms, you will have to protect
shell metacharacters if you want them treated literally.  This is in
practice difficult to do, as it's unclear how to escape which characters.
See L<perlsec> for a clean and safe example of a manual fork() and exec()
to emulate backticks safely.

On some platforms (notably DOS-like ones), the shell may not be
capable of dealing with multiline commands, so putting newlines in
the string may not get you what you want.  You may be able to evaluate
multiple commands in a single line by separating them with the command
separator character, if your shell supports that (e.g. C<;> on many Unix
shells; C<&> on the Windows NT C<cmd> shell).

Beware that some command shells may place restrictions on the length
of the command line.  You must ensure your strings don't exceed this
limit after any necessary interpolations.  See the platform-specific
release notes for more details about your particular environment.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?