How do you concatenate arrays of aliases in Perl such that the resulting array also contains aliases?
如何在Perl中连接别名数组,以便生成的数组还包含别名?
The solution that I came up with is:
我想出的解决方案是:
my ($x, $y, $z) = 1 .. 3;
my $a1 = sub {\@_}->($x);
my $a2 = sub {\@_}->($y, $z);
my $a3 = sub {\@_}->(@$a1, @$a2);
say "@$a3"; # 1 2 3
$_++ for $x, $y, $z;
say "@$a3"; # 2 3 4
What I am not crazy about is that to create $a3
I have to completely unpack $a1
and $a2
. For short arrays this isn't a problem, but as the data grows larger, it means that all array operations on aliased arrays are O(n)
, including traditionally O(1)
operations like push
or unshift
.
我并不疯狂的是创造$ a3我必须完全解开$ a1和$ a2。对于短数组,这不是问题,但随着数据变大,这意味着别名数组上的所有数组操作都是O(n),包括传统的O(1)操作,如push或unshift。
Data::Alias
could help, but it doesn't work with the latest versions of Perl. Array::RefElem
contains wrappers around the api primitives av_store
and av_push
which can be used to implement this functionality. So something like this could work:
Data :: Alias可以提供帮助,但它不适用于最新版本的Perl。 Array :: RefElem包含api原语av_store和av_push周围的包装器,可用于实现此功能。所以像这样的东西可以工作:
sub alias_push (\@@) {
if (eval {require Array::RefElem}) {
&Array::RefElem::av_push($_[0], $_) for @_[1 .. $#_]
} else {
$_[0] = sub {\@_}->(@{$_[0]}, @_[1 .. $#_])
}
}
I am interested to know if there are any other ways. Particularly if there are any other ways using only the core modules.
我很想知道是否有其他方法。特别是如果有任何其他方式仅使用核心模块。
1 个解决方案
#1
1
Is this one of the cases where you might want a linked list in Perl? Steve Lembark has a talk about the various cases where people should reconsider rolling and unrolling arrays.
这是您在Perl中可能需要链表的情况吗? Steve Lembark谈论了人们应该重新考虑滚动和展开数组的各种情况。
I'm curious why you have to do things this way though. Not that I suspect anything odd; I'm just curious about the problem.
我很好奇为什么你必须这样做。不是我怀疑有什么奇怪的;我只是对这个问题感到好奇。
#1
1
Is this one of the cases where you might want a linked list in Perl? Steve Lembark has a talk about the various cases where people should reconsider rolling and unrolling arrays.
这是您在Perl中可能需要链表的情况吗? Steve Lembark谈论了人们应该重新考虑滚动和展开数组的各种情况。
I'm curious why you have to do things this way though. Not that I suspect anything odd; I'm just curious about the problem.
我很好奇为什么你必须这样做。不是我怀疑有什么奇怪的;我只是对这个问题感到好奇。