在 Perl 中,如何从子例程返回绑定的散列? [英] In Perl, how can I return a tied hash from a subroutine?
问题描述
我想要一个 perl 子例程,它通过 Tie::IxHash 模块创建并返回一个有序的散列.它看起来像这样:
I want to have a perl subroutine that creates and returns an ordered hash via the Tie::IxHash module. It looks something like this:
sub make_ordered_hash {
my @hash_contents = munge_input(@_); # I get a list of alternating keys and values
tie(my %myhash, Tie::IxHash, @hash_contents);
return %myhash;
}
现在,如果我执行 my %ordered_hash = make_ordered_hash(@input_stuff)
,那么 %ordered_hash 会实际绑定,还是将 %myhash 解包到一个列表中,然后创建一个新的(普通的,无序)来自该列表的哈希?如果我不能以这种方式返回绑定的哈希,我可以返回对一个的引用吗?也就是说,我可以通过让 make_ordered_hash 返回 \%myhash
来修复它吗?
Now, if I do my %ordered_hash = make_ordered_hash(@input_stuff)
, will %ordered_hash actually be tied, or will it unpack %myhash, into a list and then create a new (ordinary, unordered) hash from that list? If I can't return a tied hash in this way, can I return a reference to one? That is, can I fix it by having make_ordered_hash return \%myhash
instead?
推荐答案
没有.当您这样做时,您返回的是哈希内容的副本,并且该副本没有绑定,正如您在第二段中推测的那样.
No. What you return when you do that is a COPY of the hash contents, and that copy is NOT tied, just as you surmised in the second paragraph.
你也是正确的,为了实现你的结果,你需要返回一个对绑定哈希的引用:return \%myhash;
You are also correct in that to achieve you result, you need to return a refernce to a tied hash instead: return \%myhash;
示例
use Tie::IxHash;
sub make_ordered_hash {
my @hash_contents = (1,11,5,15,3,13);
tie(my %myhash, Tie::IxHash, @hash_contents);
return %myhash;
}
sub make_ordered_hashref {
my @hash_contents = (1,11,5,15,3,13);
tie(my %myhash, Tie::IxHash, @hash_contents);
return \%myhash;
}
my @keys;
my %hash1 = make_ordered_hash();
@keys = keys %hash1;
print "By Value = @keys\n";
my $hash2 = make_ordered_hashref();
@keys = keys %$hash2;
print "By Reference = @keys\n";
结果:
By Value = 1 3 5
By Reference = 1 5 3
这篇关于在 Perl 中,如何从子例程返回绑定的散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!