【问题标题】:How to reference and dereference a hash of hashes for subroutines in Perl如何在 Perl 中引用和取消引用子例程的哈希值
【发布时间】:2013-02-06 07:51:37
【问题描述】:

有谁知道如何取消引用散列的散列,以便我可以在我的子例程中使用它。如您所见,我无法在我的子例程中访问我的 Hash of Hashes 数据结构。

my $HoH_ref = \%HoH;     # reference the hash of hashes

for(@sorted) {
print join("\t", $_, get_num($_, $HoH_ref))
}

sub get_num {
    my ($foo) = shift;
    my $HoH_ref = shift;
    my %HoH = %{$HoH_ref};    # dereference the hash of hashes
    my $variable = %HoH{$foo}{'name'};
    # do stuff
    return;
    }

我在%HoH{ 附近的倒数第二行%HoH{$protein}{'degree'} 上遇到语法错误,并且哈希的哈希无法识别来自%HoH$protein 键。我收到错误消息:Global symbol "$protein" requires explicit package name。谢谢

【问题讨论】:

标签: perl reference subroutine dereference hash-of-hashes


【解决方案1】:

访问哈希元素的语法是$hash{KEY},而不是%hash{KEY}

my %HoH = %{$HoH_ref};
my $variable = $HoH{$foo}{name};
               ^
               |

但是复制整个哈希是愚蠢的。使用

my $variable = $HoH_ref->{$foo}{name};

【讨论】:

    猜你喜欢
    • 2011-01-17
    • 2011-10-11
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2011-10-22
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多