如何引用具有变量名称的哈希?

时间:2009-08-06 19:14:33

标签: perl hash

我有三个名为%hash1%hash2%hash3的哈希。我需要通过变量引用每个哈希,我不知道该怎么做。

#!/usr/bin/perl

# Hashes %hash1, %hash2, %hash3 are populated with data.

@hashes = qw(hash1 hash2 hash3);
foreach $hash(@hashes){
    foreach $key(keys $$hash){
          .. Do something with the hash key and value
    }
}

我知道这是一个相当简单,比较无聊的问题,所以我为此道歉。

2 个答案:

答案 0 :(得分:17)

这应该适合你。

#!/usr/bin/perl
use strict;
use warnings;

my( %hash1, %hash2, %hash3 );

# ...

# load up %hash1 %hash2 and %hash3

# ...

my @hash_refs = ( \%hash1, \%hash2, \%hash3 );

for my $hash_ref ( @hash_refs ){
  for my $key ( keys %$hash_ref ){
    my $value = $hash_ref->{$key};

    # ...

  }
}

它使用哈希引用,而不是使用符号引用。很容易使符号引用错误,并且很难调试。

这是你可以使用符号引用的方法,但我会反对它。

#!/usr/bin/perl
use strict;
use warnings;

# can't use 'my'
our( %hash1, %hash2, %hash3 );

# load up the hashes here

my @hash_names = qw' hash1 hash2 hash3 ';
for my $hash_name ( @hash_names ){
  print STDERR "WARNING: using symbolic references\n";

  # uh oh, we have to turn off the safety net
  no strict 'refs';

  for my $key ( keys %$hash_name ){
    my $value = $hash_name->{$key};

    # that was scary, better turn the safety net back on
    use strict 'refs';

    # ...

  }

  # we also have to turn on the safety net here
  use strict 'refs';

  # ...

}

答案 1 :(得分:1)

要通过引用引用哈希,您可以使用以下两种方法之一。

my $ref_hash = \%hash;

或创建匿名引用哈希

my $ref_hash = { 
    key => value, 
    key => value
}

现在,为了访问此哈希,您需要取消引用该变量或使用箭头语法。

示例1(箭头语法)

print $ref_hash->{key};

示例2

print ${$ref_hash}{key};

我希望有所帮助。

相关问题