标量与列表赋值运算符 [英] Scalar vs List Assignment Operator

查看:35
本文介绍了标量与列表赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我理解以下片段:

Please help me understand the following snippets:

  • my $count = @array;
  • 我的@copy = @array;
  • my ($first) = @array;
  • (my $copy = $str) =~ s/\/\\/g;
  • my ($x) = f() or die;
  • my $count = () = f();
  • print($x = $y);
  • print(@x = @y);

推荐答案

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

The symbol = is compiled into one of two assignment operators:

  • 如果 = 的左侧 (LHS) 是某种聚合,则使用 列表赋值运算符 (aassign).
  • 否则使用标量赋值运算符 (sassign).
  • A list assignment operator (aassign) is used if the left-hand side (LHS) of a = is some kind of aggregate.
  • A scalar assignment operator (sassign) is used otherwise.

以下内容被视为聚合:

  • 括号中的任何表达式(例如 (...))
  • 一个数组(例如@array)
  • 一个数组切片(例如 @array[...])
  • 哈希(例如 %hash)
  • 一个哈希切片(例如 @hash{...})
  • myourlocal
  • 开头的任何上述内容
  • Any expression in parentheses (e.g. (...))
  • An array (e.g. @array)
  • An array slice (e.g. @array[...])
  • A hash (e.g. %hash)
  • A hash slice (e.g. @hash{...})
  • Any of the above preceded by my, our or local

运算符之间有两个不同之处.

There are two differences between the operators.

这两个运算符在其操作数被评估的上下文中有所不同.

The two operators differ in the context in which their operands are evaluated.

  • 标量赋值在标量上下文中计算其两个操作数.

  • 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 two operators differ in what they return.

    • 标量赋值...

    • The scalar assignment ...

    • ... 在标量上下文中将其 LHS 计算为左值.

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

    # The s/// operates on $copy.
    (my $copy = $str) =~ s/\/\\/g;
    

  • ... 在列表上下文中将其 LHS 计算为左值.

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

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

  • 列表赋值...

    • ... 在标量上下文中计算其 RHS 返回的标量数.

    • ... 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();
    

  • ... 在列表上下文中计算其 LHS 作为左值返回的标量.

  • ... in list context evaluates to the scalars returned by its LHS as lvalues.

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

  • 这篇关于标量与列表赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆