0

最近我在博客上看到了这个 Perl 表达式,无法抓住它的目的。

    my $success = 1; 
    $success &&= $insert_handle->execute($first, $last, $department); 
    $success &&= $update_handle->execute($department);
4

3 回答 3

9
EXPR1 &&= EXPR2;

简称

EXPR1 = EXPR1 && EXPR2;

(除了EXPR1只评估一次。*)

提供的代码

my $success = 1; 
$success &&= $insert_handle->execute($first, $last, $department); 
$success &&= $update_handle->execute($department);

也可以写成:

my $success = 0;
if ($insert_handle->execute($first, $last, $department)) {
   if ($update_handle->execute($department)) {
      $success = 1;
   }
}

或者

my $success = $insert_handle->execute($first, $last, $department)
           && $update_handle->execute($department);

* - 如果EXPR1有副作用,这很重要,如果它是一个神奇的变量或左值子,这很可能发生。

my $x = 3;      # Prints:
print("$x\n");  # 3

sub x() :lvalue { print("x\n"); $x }

x &&= 4;        # x
print("$x\n");  # 4

x = x && 5;     # x x
print("$x\n");  # 5
于 2012-09-25T19:07:11.493 回答
3

这是一个很长的说法。

 my $success =
     $insert_handle->execute($first, $last, $department)
     && $update_handle->execute($department);
于 2012-09-25T19:10:36.717 回答
1

可能 : -

my $success = 1; 
$success = $success && $insert_handle->execute($first, $last, $department); 
$success = $success && $update_handle->execute($department);

如同 : -

a += b  
// is equivalent to
a = a + b
于 2012-09-25T19:05:53.220 回答