如何在 Perl 中连接别名数组?

发布于 2024-09-26 05:27:27 字数 945 浏览 0 评论 0原文

如何在 Perl 中连接别名数组以使结果数组也包含别名?

我想出的解决方案是:

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

我不喜欢的是要创建 $a3 我必须完全解压 $a1$a2.对于短数组,这不是问题,但随着数据变大,这意味着别名数组上的所有数组操作都是 O(n),包括传统上的 O(1) code> 操作,例如 pushunshift

Data::Alias 可以提供帮助,但它不适用于最新版本的 Perl。 Array::RefElem 包含 API 原语 av_storeav_push 的包装器,可用于实现此功能。所以这样的事情是可行的:

sub alias_push (\@@) {
    if (eval {require Array::RefElem}) {
       &Array::RefElem::av_push($_[0], $_) for @_[1 .. $#_]
    } else {
       $_[0] = sub {\@_}->(@{$_[0]}, @_[1 .. $#_])
    }
}

我有兴趣知道是否还有其他方法。特别是如果有任何其他方法仅使用核心模块的话。

How do you concatenate arrays of aliases in Perl such that the resulting array also contains aliases?

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.

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:

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

你的笑 2024-10-03 05:27:27

这是您可能需要 Perl 中的链接列表的情况之一吗? Steve Lembark 发表演讲,讨论人们应该重新考虑滚动和展开数组的各种情况。

我很好奇为什么你必须这样做。并不是说我怀疑有什么奇怪的事情;我只是对这个问题感到好奇。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文