在Perl中,如何使用变量的内容作为哈希的名称?

时间:2014-04-08 15:12:59

标签: perl hash strict

以下代码仅适用于不严格的代码。 任何人都可以提出更好的方法吗?

%hash5=('key5', 5);
my $hash_name = 'hash5';
print $$hash_name{'key5'}, "\n";

我的目标:我不知道哈希名称。我只知道,它是存储的 变量$ hash_name。人们一直在建议:

 my $hashref = \%hashABC;

这要求我知道哈希名称是'%hashABC'。 在上面使用这个例子,我想做某事:

 my $hash_name = 'hashABC'; 
 my $hashref = \%$hash_name; # not possible, hope u get the aim

现在我不再需要知道哈希的名称了。 这就是我想要的。

很多人! (perl 5)

3 个答案:

答案 0 :(得分:7)

不是按名称引用哈希,而是使用引用。

# Here is our hash
my %hash = (key => 5);
# we make a reference to the hash
# this is like remembering the name of the variable, but safe
my $hashref = \%hash;

# here are two ways to access values in the referenced hash
say $$hashref{key};
say $hashref->{key}; # prefer this

或者,保留哈希散列,以便您可以按名称查找项目:

# here is our hash again
my %hash = (key => 5);
# and here is a hash that maps names to hash references
my %hash_by_name;
# we remember the %hash as "hash5"
$hash_by_name{hash5} = \%hash;

# now we can access an element in that hash
say $hash_by_name{hash5}{key};

# we can also have a variable with the name:
my $name = "hash5";
say $hash_by_name{$name}{key};

详细了解perlreftut中的参考资料。

答案 1 :(得分:0)

在这种情况下,暂时禁用strict看起来是最好的解决方案,你可以这样做

#!/usr/bin/perl

use strict;
use warnings;

our %hash5=('key5', 5);
my $hash_name = 'hash5';

my $hash_ref;

{
    no strict "refs";
    $hash_ref = \%$hash_name;
}

print $hash_ref->{key5}, "\n";

注意:要使其正常工作,%hash5必须是全局变量。

答案 2 :(得分:0)

我不知道%hash_name中的数据来自哪里。您是否已阅读并将其存储在%hash_name中?如果是这样,也许更简单的解决方案是修改程序以读入散列哈希(正如许多人所建议的那样),而不是读入全局变量:

my %data = (
    hash_name => get_data(),
);
# and then ...
my $name = get_name(); # e.g., 'hash_name'
my $data = $data{ $name } or do {
    # error handling
    ...
};

请记住,use strict强加的限制根本不适用于哈希:-)

的键
相关问题