gpt4 book ai didi

perl - 如何保留嵌套 Perl 哈希的插入顺序并使用克隆?

转载 作者:行者123 更新时间:2023-12-01 01:33:01 27 4
gpt4 key购买 nike

我正在使用 IxHash 来记住哈希的插入顺序。但是当使用克隆复制哈希时,我得到一个空哈希。

use strict;
use Switch;
use Data::Dumper;
use Clone qw(clone);
use Tie::Autotie 'Tie::IxHash';

our %h_basic_values;
my $t = tie our(%h_inner_hash), "Tie::IxHash";
my $t1 = tie our(%h_inner_hash1) , "Tie::IxHash";

%h_inner_hash = (
'in_1' => 'val_1',
'in_2' => 'val_2',
'in_3' => 'val_3'
);

%h_inner_hash1 = (
'innnn_1' => 'vallll_1',
'innnn_2' => 'vallll_2',
'innnn_3' => 'vallll_3',
);

$h_inner_hash{in_4}{inn_1} = "vall_1";
$h_inner_hash{in_4}{inn_2} = "vall_2";
$h_inner_hash{in_4}{inn_3} = "vall_3";
$h_inner_hash{in_4}{inn_4} = "vall_4";
$h_inner_hash{in_4}{inn_5}{innn_1} = 'valll_1';
$h_inner_hash{in_4}{inn_5}{innn_2} = "valll_2";
$h_inner_hash{in_4}{inn_5}{innn_3} = "valll_3";
$h_inner_hash{in_4}{inn_5}{innn_4} = "valll_4";

$h_inner_hash{in_4}{inn_5}{innn_5} = clone(\%h_inner_hash1);
print Dumper(\%h_inner_hash);

在 $h_inner_hash{in_4}{inn_5}{innn_5} 我得到一个空哈希。

最佳答案

这不是克隆的问题,也不是%h_inner_hash1 的问题。被捆绑。这是一个 limitation of Tie::Autotie .从它的 perldoc :

BUGS

[...]

Assigning a reference

In the Tie::IxHash example, you cannot do:

$hash{jeff} = {
age => 22,
lang => 'Perl',
brothers => 3,
sisters => 4,
};

because that creates a hash reference, not an object of Tie::IxHash. This hash reference ends up being destroyed anyway, and replaced with a Tie::IxHash object that points to an empty hash.



作为一种方法,您可以手动复制 %h_inner_hash1逐个键:
$h_inner_hash{in_4}{inn_5}{innn_5}{$_} = $h_inner_hash1{$_} for keys %h_inner_hash1;

或者您可以手动将哈希的每一层绑定(bind)到 Tie::IxHash,而不是使用 Tie::Autotie。

关于perl - 如何保留嵌套 Perl 哈希的插入顺序并使用克隆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3594144/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com