Perl 如何使用变量名引用哈希?
我有三个哈希,分别是Perl 如何使用变量名引用哈希?,perl,hash,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
%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
}
}
我知道这是一个相当简单的问题,相对来说是一个没有意义的问题,所以我对此表示歉意。这应该适合你
#!/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';
# ...
}
要通过引用引用哈希,可以使用以下两种方法之一
my $ref_hash = \%hash;
或者创建一个匿名引用哈希
my $ref_hash = {
key => value,
key => value
}
现在,为了访问这个散列,您需要取消引用变量或使用箭头语法
示例1(箭头语法)
例2
print ${$ref_hash}{key};
我希望这能有所帮助。请看一下
perldoc perlreftut
,了解Perl中引用的良好介绍(如何创建它们,如何从它们中获取值,何时可以使用它们)。请确保阅读了许多多+1,因为它们没有显示操作如何使用符号引用;-)。。。初学者通常认为他们想要一个包含变量名称的变量。很抱歉添加了可怕的符号引用版本:-(虽然,希望我已经展示了这样做的麻烦。为什么这是一个如此常见的问题?在哪里使用这个?被认为是一个好主意?问题是关于使用象征性引用。@Brad:问题是关于完成工作。我相信他会很乐意使用任何有效的工具。:)
print ${$ref_hash}{key};