Perl 哈希切片、复制 x 运算符和子参数
好的,我了解 Perl 哈希切片和 “x”运算符 在 Perl 中,但有人可以解释 这里(稍微简化)?
sub test{
my %hash;
@hash{@_} = (undef) x @_;
}
对 sub 的示例调用:
test('one', 'two', 'three');
这一行让我感到困惑:
@hash{@_} = (undef) x @_;
它正在创建一个哈希,其中键是 sub 的参数并初始化为 undef,因此:
%hash:
'one' =>未定义, '二' =>未定义, '三' => undef
x 运算符的右值应该是一个数字; @_ 是如何解释为子参数数组的长度的?我希望你至少必须这样做:
@hash{@_} = (undef) x scalar @_;
Ok, I understand perl hash slices, and the "x" operator in Perl, but can someone explain the following code example from here (slightly simplified)?
sub test{
my %hash;
@hash{@_} = (undef) x @_;
}
Example Call to sub:
test('one', 'two', 'three');
This line is what throws me:
@hash{@_} = (undef) x @_;
It is creating a hash where the keys are the parameters to the sub and initializing to undef, so:
%hash:
'one' => undef,
'two' => undef,
'three' => undef
The rvalue of the x operator should be a number; how is it that @_ is interpreted as the length of the sub's parameter array? I would expect you'd at least have to do this:
@hash{@_} = (undef) x scalar @_;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要弄清楚这段代码,您需要了解三件事:
重复运算符。
x
运算符是重复运算符。在列表上下文中,如果运算符的左侧参数括在括号中,它将重复列表中的项目:标量上下文中的数组。当在标量上下文中使用数组时,它将返回其大小。 x 运算符将标量上下文强加在其右侧参数上。
哈希切片。哈希切片语法提供了一种方法一次访问多个哈希项。哈希片可以检索哈希值,也可以对其进行分配。在当前的情况下,我们分配给一个哈希片。
做同样事情的不太晦涩的方法:
To figure out this code you need to understand three things:
The repetition operator. The
x
operator is the repetition operator. In list context, if the operator's left-hand argument is enclosed in parentheses, it will repeat the items in a list:Arrays in scalar context. When an array is used in scalar context, it returns its size. The
x
operator imposes scalar context on its right-hand argument.Hash slices. The hash slice syntax provides a way to access multiple hash items at once. A hash slice can retrieve hash values, or it can be assigned to. In the case at hand, we are assigning to a hash slice.
Less obscure ways to do the same thing:
在标量上下文中,数组计算其长度。来自 perldoc perldata :
虽然我目前找不到更多关于它的信息,但似乎复制运算符在标量上下文中计算其第二个参数,导致数组计算其长度。
In scalar context, an array evaluates to its length. From
perldoc perldata
:Although I cannot find more information on it currently, it seems that the replication operator evaluates its second argument in scalar context, causing the array to evaluate to its length.