问题描述
请帮助我理解以下代码段:
Please help me understand the following snippets:
-
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);
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);
推荐答案
符号=
被编译为两个赋值运算符之一:
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.
以下内容被认为是合计的:
The following are considered to be aggregates:
- 括号中的任何表达式(例如
(...)
) - 一个数组(例如
@array
) - 数组切片(例如
@array[...]
) - 哈希(例如
%hash
) - 哈希切片(例如
@hash{...}
) - 以上任何内容前面均带有
my
,our
或local
- 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
orlocal
运算符之间有两个区别.
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);
这篇关于标量vs列表赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!