如何在 Perl 中引用数组切片?

发布于 2024-08-12 18:59:12 字数 329 浏览 5 评论 0原文

如何获取对数组切片的引用,以便在修改切片引用的元素时,原始数组也会被修改?

以下代码由于 @_ 别名魔法而有效,但对我来说似乎有点黑客:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

彼岸花似海 2024-08-19 18:59:12

Data::Alias 似乎能够执行您想要的操作:

#!/usr/bin/perl

use strict; use warnings;

use Data::Alias;

my @x = 1 .. 10;

print "@x\n";

my $y = alias [ @x[2 ..7] ];
@$y[0, -1] = qw/ < > /;

print "@x\n";

输出:

1 2 3 4 5 6 7 8 9 10
1 2 < 4 5 6 7 > 9 10

Data::Alias seems to be able to do what you want:

#!/usr/bin/perl

use strict; use warnings;

use Data::Alias;

my @x = 1 .. 10;

print "@x\n";

my $y = alias [ @x[2 ..7] ];
@$y[0, -1] = qw/ < > /;

print "@x\n";

Output:

1 2 3 4 5 6 7 8 9 10
1 2 < 4 5 6 7 > 9 10
誰認得朕 2024-08-19 18:59:12

你就是这样做的,是的。仔细想想,这并不是什么黑客行为。它只是使用 Perl 的功能将任意左值组装到数组中,然后引用它。

您甚至可以使用它来推迟哈希值的创建:

$ perl -wle'my %foo; my $foo = sub{\@_}->($foo{bar}, $foo{baz}); print "before: ", keys %foo; $foo->[1] = "quux"; print "after: ", keys %foo'
before: 
after: baz

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:

$ perl -wle'my %foo; my $foo = sub{\@_}->($foo{bar}, $foo{baz}); print "before: ", keys %foo; $foo->[1] = "quux"; print "after: ", keys %foo'
before: 
after: baz
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文