2

我是 Perl 的新手。我仍在尝试学习它的语法。我见过有人在 Perl 中使用//and //=,但我在网上找不到任何解释这一点的资源。

有人可以用外行的话向我解释它到底是什么意思吗?它实际上做了什么?

4

2 回答 2

7

As kjprice mentioned, // is the logical 'defined or' operator and is documented here on the perlop page and the relevant excerpt is

it's exactly the same as ||, except that it tests the left hand side's definedness instead of its truth. Thus, EXPR1 // EXPR2 returns the value of EXPR1 if it's defined, otherwise, the value of EXPR2 is returned.

You can think of

my $var = EXPR1 // EXPR2;

as a short hand way of writing:

my $var;
if ( defined EXPR1 ) {
    $var = EXPR1;
} else {
    $var = EXPR2;
}

I often use this to either assign a default value to a variable unless a supplied by command line or config file value is supplied. Something like:

my $var = $config_version // 'foo';

The //= is a variation of this with an assignemnt mixed in. That same perlop page says this:

Modifying an assignment is equivalent to doing the assignment and then modifying the variable that was assigned to.

For //= that means instead of writing something like

my $var = EXPR1 // EXPR2;

You could write

my $var = EXPR1;
$var //= EXPR2;

and get equivalent values.

于 2013-08-07T01:49:05.850 回答
2

perldoc perlop

逻辑定义或

尽管它在 C 中没有直接的等价物,但 Perl 的//运算符与其 C 风格的或有关。实际上,它与 完全相同||,只是它测试的是左侧的定义性而不是其真实性。因此,如果定义了则EXPR1 // EXPR2返回 的值EXPR1,否则EXPR2返回 的值。(EXPR1在标量上下文中评估,EXPR2在其自身的上下文中//)。通常,这是相同的结果defined(EXPR1) ? EXPR1 : EXPR2(除了三元运算符形式可以用作左值,而EXPR1 // EXPR2不能)。这对于为变量提供默认值非常有用。$a如果您确实想测试是否定义了和中的至少一个$b,请使用defined($a // $b).

所以:

 $NODEFINED // $DEFINED # will return the value of defined

 $DEFINED1 // $DEFINED2 # will return the value of $DEFINED1

 $a //= $b;

是以下的简写:

 $a = $a // $b;

仅当未定义$a时才会设置为该值。$b$a

$a //= 42;表单对于为可能尚未定义的变量设置默认值很有用。

于 2013-08-07T01:43:24.250 回答