在 Perl 中合并内部哈希

发布于 2024-09-29 19:35:53 字数 222 浏览 0 评论 0原文

我有 3 维哈希和一个 2 维哈希,我想将 2 维哈希与 3 维哈希的内部哈希之一合并,就像这样,这类似于我合并一对 2d 哈希的操作:

my %3dhash;
my %2dhash;
my $key = "some string";
%3dhash{$key} = ($3dhash{$key}, %2dhash);

但是我尝试了一下,还是不行。我应该做什么?

I have 3 dimensional hash and a 2 dimensional hash, and I want to merge the 2 dimensional hash with one of the inner hashes of the 3 dimensional hash, something like this, which is similar to what I do to merge a pair of 2d hashes:

my %3dhash;
my %2dhash;
my $key = "some string";
%3dhash{$key} = ($3dhash{$key}, %2dhash);

But when I tried that it didn't work. What should I be doing?

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

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

发布评论

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

评论(1

雪若未夕 2024-10-06 19:35:53

请尝试以下操作:

my %hash3d;
my %hash2d;
....
my $key = "some string";
$hash3d{$key} = { %{ $hash3d{$key} }, %hash2d };

Perl 中的变量不能以数字开头,因此我重命名了变量。现有哈希周围的 %{ ... } 将其扩展为列表。此列表与 %hash2d 中的列表合并。该列表周围的 { ... } 是匿名哈希引用构造函数,它创建一个新的哈希引用,然后将其存储在 $hash3d{$key}

Try the following:

my %hash3d;
my %hash2d;
....
my $key = "some string";
$hash3d{$key} = { %{ $hash3d{$key} }, %hash2d };

Variables in Perl can't start with a number, so I renamed the variables. The %{ ... } around the existing hash expands it as a list. This list flattens with the list from %hash2d. The { ... } around that list is the anonymous hash reference constructor, which creates a new hash reference that is then stored in $hash3d{$key}

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