我有三个名为哈希%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
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这是一个相当简单,比较无聊的问题所以我为此道歉.
Bra*_*ert 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};
# ...
}
}
Run Code Online (Sandbox Code Playgroud)
它使用哈希引用,而不是使用符号引用.很容易使符号引用错误,并且很难调试.
这是你如何使用符号引用,但我会建议反对它.
#!/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';
# ...
}
Run Code Online (Sandbox Code Playgroud)