标量赋值运算符 vs 列表赋值运算符

5
请帮忙理解以下代码片段:
  • my $count = @array;
  • my @copy = @array;
  • my ($first) = @array;
  • (my $copy = $str) =~ s/\\/\\\\/g;
  • my ($x) = f() or die;
  • my $count = () = f();
  • print($x = $y);
  • print(@x = @y);

你能加上一个明确的问题吗?目前没有一个。 - ysth
my ($first) = @array - mob
@ysth,技术上有8个问题。但请随意重新编写。 - ikegami
@mob,当然可以!已添加。 - ikegami
1个回答

7

[这个答案也可以在表格格式中找到这里]

符号=编译成两种赋值运算符之一:

  • 如果=的左侧是某种集合,则使用列表赋值运算符aassign)。
  • 否则,使用标量赋值运算符sassign)。

以下被视为集合:

  • 括号中的任何表达式(例如(...)
  • 数组(例如@array
  • 数组切片(例如@array[...]
  • 哈希(例如%hash
  • 哈希切片(例如@hash{...}
  • 以上任何一个前面加上myourlocal

这两个运算符有两个不同之处。

操作数的上下文

这两个运算符在评估其操作数的上下文方面有所不同。

  • The scalar assignment evaluates both of its operands in scalar context.

      # @array evaluated in scalar context.
      my $count = @array;
    
  • The list assignment evaluates both of its operands in list context.

      # @array evaluated in list context.
      my @copy = @array;
    

      # @array evaluated in list context.
      my ($first) = @array;
    

返回值

这两个运算符返回的结果不同。

  • The scalar assignment ...

    • ... in scalar context evaluates to its LHS as an lvalue.

        # The s/// operates on $copy.
        (my $copy = $str) =~ s/\\/\\\\/g;
      
    • ... in list context evaluates to its LHS as an lvalue.

        # Prints $x.
        print($x = $y);
      
  • The list assignment ...

    • ... in scalar context evaluates to the number of scalars returned by its RHS.

        # Only dies if f() returns an empty list.
        # This does not die if f() returns a
        # false scalar like zero or undef.
        my ($x) = f() or die;
      

        # $counts gets the number of scalars returns by f().
        my $count = () = f();
      
    • ... in list context evaluates to the scalars returned by its LHS as lvalues.

        # Prints @x.
        print(@x = @y);
      

更改为只说数组或哈希或数组或哈希切片,以包括postderef语法。 - ysth
@ysth,啊是的,当这篇文章最初写作时它们还不存在。 - ikegami

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接