说我有一个数组和一个多维哈希。我想以递归方式查看数组中的值是否作为哈希中的键存在。有没有比以下更好的方式? (例子编辑自Perl Maven Perl Maven)。
请注意以下几点:
FooBar
中仅存在Mathematics
和%grades
; @array=("FooBar","Mathematics")
查看$myhash{"FooBar"}{"Mathematics"}
处的值;如果失败,请查看" FooBar"或者#34;数学"存在于哈希的第二级,即$myhash{"otherkeys"}{"Mathematics"}
或$myhash{"otherkeys"}{"FooBar"}
)。示例:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dump;
my @subjectsandnames=("FooBar","ThatBar","Mathematics","Biology","Physics");
my %grades;
$grades{"FooBar"}{Mathematics} = 12;
$grades{"FooBar"}{Literature} = 99;
$grades{"PetiBar"}{Literature} = 87;
$grades{"PetiBar"}{Mathematics} = 13;
$grades{"PetiBar"}{Art} = 93;
foreach my $name (sort keys %grades) {
my @possible = grep defined, map { $grades{$_}} @subjectsandnames; #sees matches at first level
dd @possible;
foreach my $subject (sort keys %{$grades{$name}}){
my @possible2 = grep defined, map { $grades{$name}{$_}} @subjectsandnames; #sees matches at second level
dd @possible2;
}
}
答案 0 :(得分:1)
不详细了解您的数据和情况,很难提供完整的建议。
但是,请说您只想查看最深级别的键是否等于您的某个主题列表。然后递归散列哈希将是一个可能的解决方案,如下所示:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dump;
my @subjectsandnames = qw(FooBar ThatBar Mathematics Biology Physics);
my %grades = (
FooBar => {
Mathematics => 12,
Literature => 99,
},
PetiBar => {
Literature => 87,
Mathematics => 13,
Art => 93,
},
);
recurse_hash(\%grades);
sub recurse_hash {
my ($hashref, @keys) = @_;
for my $key (sort keys %$hashref) {
my $val = $hashref->{$key};
if (ref $val) {
recurse_hash($val, @keys, $key);
} elsif (grep {$key eq $_} @subjectsandnames) {
print "@keys $key $val\n";
}
}
}
输出:
FooBar Mathematics 12
PetiBar Mathematics 13