0

I have a set of pre-defined hash tables and I want to reference one of those hashes using a variable name and access a key value. The following code just returns null even though the hash is populated. What am I doing wrong here, or is there a better way to achieve this?

my %TEXT1 = (1 => 'Hello World',);
my %TEXT2 = (1 => 'Hello Mars',);
my %TEXT3 = (1 => 'Hello Venus',);

my $hash_name = 'TEXT1';

my $hash_ref = \%$hash_name;
print ${$hash_ref}{1};  #prints nothing
4

3 回答 3

5

你的代码工作得很好*

%TEXT = (1 => abc, 42 => def);
$name = 'TEXT';
print ref($name);         #  ""
no strict 'refs';
print ${$name}{1};        #  "abc"
print $name->{42}         #  "def"
$ref = \%$name;
print ref($ref);          #  "HASH"
print $ref->{1};          #  "abc"
print ${$ref}{42};        #  "def"

你做错的主要事情是让你的代码变得无法维护,这就是为什么这种事情是不允许的use strict 'refs'

* - 除非你在 下运行use strict 'refs',你应该是

于 2017-10-21T23:57:05.760 回答
3

使用哈希来包含您的哈希。

my %texts = (
    TEXT1 => { 1 => 'Hello world', },
    TEXT2 => { 1 => 'Hello Mars', },
    TEXT3 => { 1 => 'Hello Venus', },
)

my $hash_name = 'TEXT1';

print $texts{$hash_name}{1}, "\n";
于 2017-10-22T13:02:55.303 回答
0

以下代码分配给标量,而不是哈希:

my $hash_name = 'TEXT';

以下代码分配给哈希:

my %hash = ( alpha => 'beta', gamma => 'delta' );

要从散列中打印单个元素的值,您可以说:

print $hash{alpha}, "\n";

您可以引用该哈希并将其分配给变量:

my $hashref = \%hash;

并且您可以从该 hashref 打印单个元素:

print $hashref->{alpha}, "\n";
于 2017-10-21T23:21:06.293 回答