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

use*_*037 -3 perl hash strict

下面的代码只适用于没有严格的代码.谁能建议一个更好的方法呢?

%hash5=('key5', 5);
my $hash_name = 'hash5';
print $$hash_name{'key5'}, "\n";
Run Code Online (Sandbox Code Playgroud)

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

 my $hashref = \%hashABC;
Run Code Online (Sandbox Code Playgroud)

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

 my $hash_name = 'hashABC'; 
 my $hashref = \%$hash_name; # not possible, hope u get the aim
Run Code Online (Sandbox Code Playgroud)

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

很多人!(perl 5)

amo*_*mon 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
Run Code Online (Sandbox Code Playgroud)

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

# 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};
Run Code Online (Sandbox Code Playgroud)

详细了解参考资料perlreftut.