如何保留嵌套 Perl 哈希的插入顺序? [英] How can I retain insertion order of a nested Perl hash?

查看:41
本文介绍了如何保留嵌套 Perl 哈希的插入顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 IxHash 来记住哈希的插入顺序.

I can use IxHash to remember the insertion order of a hash.

use Tie::IxHash;

my %hash;
tie(%hash, 'Tie::IxHash');
%hash = (
  x => 10,
  z => 20,
  q => { a1 => 1, a3 => 5, a2=>2,},
  y => 30,
);

printf("keys %s\n", join(" ", keys %hash));

=> keys x z q y

嵌套散列怎么样?

printf("keys %s\n", join(" ", keys %{$hash{q}}));
keys a2 a1 a3

我怀疑答案是否定的,因为 q 哈希是匿名的,并且在 IxHash 看到之前订单就丢失了.

I suspect the answer is no as the q hash is anonymous and the order is lost before IxHash sees it.

我知道我可以在 $hash{q} 上执行 Tie,然后添加元素,但我喜欢使用单个赋值来构建哈希.

I know that I can do Tie on $hash{q} and then add the elements, but I like using the single assignment to build the hash.

有什么技巧吗?

推荐答案

有多种方法可以做到这一点,我只是将领带包装在一个子程序中,以便于内联使用:

There are multiple ways to do this, I would just wrap up the tie in a subroutine so that its easy to use inline:

use Tie::IxHash;

sub ordered_hash (%) {
    tie my %hash => 'Tie::IxHash';
    %hash = @_;
    \%hash
}

然后:

tie my %hash => 'Tie::IxHash';

%hash = (
    x => 10,
    z => 20,
    q => ordered_hash( a1 => 1, a3 => 5, a2=>2 ),
    y => 30,
);

子程序中的 (%) 原型告诉 perl 它需要一个包含偶数个元素的列表

the (%) prototype on the subroutine tells perl that it takes a list with an even number of elements

这篇关于如何保留嵌套 Perl 哈希的插入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆