perlop.pod

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

POD
1,675
字号
way to find out the home directory (assuming it's not "0") might be:

    $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
	(getpwuid($<))[7] || die "You're homeless!\n";

In particular, this means that you shouldn't use this
for selecting between two aggregates for assignment:

    @a = @b || @c;		# this is wrong
    @a = scalar(@b) || @c;	# really meant this
    @a = @b ? @b : @c;		# this works fine, though

As more readable alternatives to C<&&> and C<||> when used for
control flow, Perl provides C<and> and C<or> operators (see below).
The short-circuit behavior is identical.  The precedence of "and" and
"or" is much lower, however, so that you can safely use them after a
list operator without the need for parentheses:

    unlink "alpha", "beta", "gamma"
	    or gripe(), next LINE;

With the C-style operators that would have been written like this:

    unlink("alpha", "beta", "gamma")
	    || (gripe(), next LINE);

Use "or" for assignment is unlikely to do what you want; see below.

=head2 Range Operators

Binary ".." is the range operator, which is really two different
operators depending on the context.  In list context, it returns an
array of values counting (by ones) from the left value to the right
value.  This is useful for writing C<foreach (1..10)> loops and for
doing slice operations on arrays.  In the current implementation, no
temporary array is created when the range operator is used as the
expression in C<foreach> loops, but older versions of Perl might burn
a lot of memory when you write something like this:

    for (1 .. 1_000_000) {
	# code
    }

In scalar context, ".." returns a boolean value.  The operator is
bistable, like a flip-flop, and emulates the line-range (comma) operator
of B<sed>, B<awk>, and various editors.  Each ".." operator maintains its
own boolean state.  It is false as long as its left operand is false.
Once the left operand is true, the range operator stays true until the
right operand is true, I<AFTER> which the range operator becomes false
again.  (It doesn't become false till the next time the range operator is
evaluated.  It can test the right operand and become false on the same
evaluation it became true (as in B<awk>), but it still returns true once.
If you don't want it to test the right operand till the next evaluation
(as in B<sed>), use three dots ("...") instead of two.)  The right
operand is not evaluated while the operator is in the "false" state, and
the left operand is not evaluated while the operator is in the "true"
state.  The precedence is a little lower than || and &&.  The value
returned is either the empty string for false, or a sequence number
(beginning with 1) for true.  The sequence number is reset for each range
encountered.  The final sequence number in a range has the string "E0"
appended to it, which doesn't affect its numeric value, but gives you
something to search for if you want to exclude the endpoint.  You can
exclude the beginning point by waiting for the sequence number to be
greater than 1.  If either operand of scalar ".." is a constant expression,
that operand is implicitly compared to the C<$.> variable, the current
line number.  Examples:

As a scalar operator:

    if (101 .. 200) { print; }	# print 2nd hundred lines
    next line if (1 .. /^$/);	# skip header lines
    s/^/> / if (/^$/ .. eof());	# quote body

    # parse mail messages
    while (<>) {
        $in_header =   1  .. /^$/;
        $in_body   = /^$/ .. eof();
	# do something based on those
    } continue {
	close ARGV if eof; 		# reset $. each file
    }

As a list operator:

    for (101 .. 200) { print; }	# print $_ 100 times
    @foo = @foo[0 .. $#foo];	# an expensive no-op
    @foo = @foo[$#foo-4 .. $#foo];	# slice last 5 items

The range operator (in list context) makes use of the magical
auto-increment algorithm if the operands are strings.  You
can say

    @alphabet = ('A' .. 'Z');

to get all the letters of the alphabet, or

    $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];

to get a hexadecimal digit, or

    @z2 = ('01' .. '31');  print $z2[$mday];

to get dates with leading zeros.  If the final value specified is not
in the sequence that the magical increment would produce, the sequence
goes until the next value would be longer than the final value
specified.

=head2 Conditional Operator

Ternary "?:" is the conditional operator, just as in C.  It works much
like an if-then-else.  If the argument before the ? is true, the
argument before the : is returned, otherwise the argument after the :
is returned.  For example:

    printf "I have %d dog%s.\n", $n,
	    ($n == 1) ? '' : "s";

Scalar or list context propagates downward into the 2nd
or 3rd argument, whichever is selected.

    $a = $ok ? $b : $c;  # get a scalar
    @a = $ok ? @b : @c;  # get an array
    $a = $ok ? @b : @c;  # oops, that's just a count!

The operator may be assigned to if both the 2nd and 3rd arguments are
legal lvalues (meaning that you can assign to them):

    ($a_or_b ? $a : $b) = $c;

This is not necessarily guaranteed to contribute to the readability of your program.

Because this operator produces an assignable result, using assignments
without parentheses will get you in trouble.  For example, this:

    $a % 2 ? $a += 10 : $a += 2

Really means this:

    (($a % 2) ? ($a += 10) : $a) += 2

Rather than this:

    ($a % 2) ? ($a += 10) : ($a += 2)

=head2 Assignment Operators

"=" is the ordinary assignment operator.

Assignment operators work as in C.  That is,

    $a += 2;

is equivalent to

    $a = $a + 2;

although without duplicating any side effects that dereferencing the lvalue
might trigger, such as from tie().  Other assignment operators work similarly.
The following are recognized:

    **=    +=    *=    &=    <<=    &&=
           -=    /=    |=    >>=    ||=
           .=    %=    ^=
	         x=

Note that while these are grouped by family, they all have the precedence
of assignment.

Unlike in C, the assignment operator produces a valid lvalue.  Modifying
an assignment is equivalent to doing the assignment and then modifying
the variable that was assigned to.  This is useful for modifying
a copy of something, like this:

    ($tmp = $global) =~ tr [A-Z] [a-z];

Likewise,

    ($a += 2) *= 3;

is equivalent to

    $a += 2;
    $a *= 3;

=head2 Comma Operator

Binary "," is the comma operator.  In scalar context it evaluates
its left argument, throws that value away, then evaluates its right
argument and returns that value.  This is just like C's comma operator.

In list context, it's just the list argument separator, and inserts
both its arguments into the list.

The =E<gt> digraph is mostly just a synonym for the comma operator.  It's useful for
documenting arguments that come in pairs.  As of release 5.001, it also forces
any word to the left of it to be interpreted as a string.

=head2 List Operators (Rightward)

On the right side of a list operator, it has very low precedence,
such that it controls all comma-separated expressions found there.
The only operators with lower precedence are the logical operators
"and", "or", and "not", which may be used to evaluate calls to list
operators without the need for extra parentheses:

    open HANDLE, "filename"
	or die "Can't open: $!\n";

See also discussion of list operators in L<Terms and List Operators (Leftward)>.

=head2 Logical Not

Unary "not" returns the logical negation of the expression to its right.
It's the equivalent of "!" except for the very low precedence.

=head2 Logical And

Binary "and" returns the logical conjunction of the two surrounding
expressions.  It's equivalent to && except for the very low
precedence.  This means that it short-circuits: i.e., the right
expression is evaluated only if the left expression is true.

=head2 Logical or and Exclusive Or

Binary "or" returns the logical disjunction of the two surrounding
expressions.  It's equivalent to || except for the very low precedence.
This makes it useful for control flow

    print FH $data		or die "Can't write to FH: $!";

This means that it short-circuits: i.e., the right expression is evaluated
only if the left expression is false.  Due to its precedence, you should
probably avoid using this for assignment, only for control flow.

    $a = $b or $c;		# bug: this is wrong
    ($a = $b) or $c;		# really means this
    $a = $b || $c;		# better written this way

However, when it's a list context assignment and you're trying to use
"||" for control flow, you probably need "or" so that the assignment
takes higher precedence.

    @info = stat($file) || die;     # oops, scalar sense of stat!
    @info = stat($file) or die;     # better, now @info gets its due

Then again, you could always use parentheses.

Binary "xor" returns the exclusive-OR of the two surrounding expressions.
It cannot short circuit, of course.

=head2 C Operators Missing From Perl

Here is what C has that Perl doesn't:

=over 8

=item unary &

Address-of operator.  (But see the "\" operator for taking a reference.)

=item unary *

Dereference-address operator. (Perl's prefix dereferencing
operators are typed: $, @, %, and &.)

=item (TYPE)

Type casting operator.

=back

=head2 Quote and Quote-like Operators

While we usually think of quotes as literal values, in Perl they
function as operators, providing various kinds of interpolating and
pattern matching capabilities.  Perl provides customary quote characters
for these behaviors, but also provides a way for you to choose your
quote character for any of them.  In the following table, a C<{}> represents
any pair of delimiters you choose.  Non-bracketing delimiters use
the same character fore and aft, but the 4 sorts of brackets
(round, angle, square, curly) will all nest.

    Customary  Generic        Meaning	     Interpolates
	''	 q{}	      Literal		  no
	""	qq{}	      Literal		  yes
	``	qx{}	      Command		  yes (unless '' is delimiter)
		qw{}	     Word list		  no
	//	 m{}	   Pattern match	  yes
		qr{}	      Pattern		  yes
		 s{}{}	    Substitution	  yes
		tr{}{}	  Transliteration	  no (but see below)

Note that there can be whitespace between the operator and the quoting
characters, except when C<#> is being used as the quoting character.
C<q#foo#> is parsed as being the string C<foo>, while C<q #foo#> is the
operator C<q> followed by a comment. Its argument will be taken from the
next line. This allows you to write:

    s {foo}  # Replace foo
      {bar}  # with bar.

For constructs that do interpolation, variables beginning with "C<$>"
or "C<@>" are interpolated, as are the following sequences. Within
a transliteration, the first ten of these sequences may be used.

    \t		tab             (HT, TAB)
    \n		newline         (NL)
    \r		return          (CR)
    \f		form feed       (FF)
    \b		backspace       (BS)
    \a		alarm (bell)    (BEL)
    \e		escape          (ESC)
    \033	octal char
    \x1b	hex char
    \c[		control char

    \l		lowercase next char
    \u		uppercase next char
    \L		lowercase till \E
    \U		uppercase till \E
    \E		end case modification
    \Q		quote non-word characters till \E

If C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u>
and C<\U> is taken from the current locale.  See L<perllocale>.

All systems use the virtual C<"\n"> to represent a line terminator,
called a "newline".  There is no such thing as an unvarying, physical
newline character.  It is an illusion that the operating system,
device drivers, C libraries, and Perl all conspire to preserve.  Not all
systems read C<"\r"> as ASCII CR and C<"\n"> as ASCII LF.  For example,
on a Mac, these are reversed, and on systems without line terminator,
printing C<"\n"> may emit no actual data.  In general, use C<"\n"> when
you mean a "newline" for your system, but use the literal ASCII when you
need an exact character.  For example, most networking protocols expect

⌨️ 快捷键说明

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