在Perl中,如何从子例程返回绑定的哈希?

时间:2010-10-28 23:24:59

标签: perl return-type

我想要一个perl子例程,它通过Tie :: IxHash模块创建并返回一个有序的哈希。它看起来像这样:

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来修复它吗?

1 个答案:

答案 0 :(得分:6)

没有。当你这样做时你返回的是哈希内容的COPY,并且该副本没有绑定,正如你在第二段中推测的那样。

为了达到你的结果,你也是正确的,你需要返回引用绑定哈希: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