如何在 Perl 中引用数组切片?
如何获取对数组切片的引用,以便在修改切片引用的元素时,原始数组也会被修改?
以下代码由于 @_
别名魔法而有效,但对我来说似乎有点黑客:
my @a = 1 .. 10;
my $b = sub{\@_}->(@a[2..7]);
@$b[0, -1] = qw/ < > /;
print "@a\n";
# 1 2 < 4 5 6 7 > 9 10
有人有更好/更快的方法吗?
编辑:上面的代码示例只是为了说明 @a 和 $b 之间所需的关系,它绝不反映此功能在生产代码中的使用方式。
How would you take a reference to an array slice such that when you modify elements of the slice reference, the original array is modified?
The following code works due to @_
aliasing magic, but seems like a bit of a hack to me:
my @a = 1 .. 10;
my $b = sub{\@_}->(@a[2..7]);
@$b[0, -1] = qw/ < > /;
print "@a\n";
# 1 2 < 4 5 6 7 > 9 10
Anyone have a better / faster way?
Edit: the code example above is simply to illustrate the relationship required between @a and $b, it in no way reflects the way this functionality will be used in production code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Data::Alias 似乎能够执行您想要的操作:
输出:
Data::Alias seems to be able to do what you want:
Output:
你就是这样做的,是的。仔细想想,这并不是什么黑客行为。它只是使用 Perl 的功能将任意左值组装到数组中,然后引用它。
您甚至可以使用它来推迟哈希值的创建:
That's how you do it, yes. Think about it for a bit and it's not such a hack; it is simply using Perl's feature for assembling arbitrary lvalues into an array and then taking a reference to it.
You can even use it to defer creation of hash values: