试试下面的代码,这是一个真实而完整的脚本:
#!/usr/bin/env perl
use strict;
use warnings;
my $job = {
'opstat' => 'ok',
'response' => {
'currency' => 'USD',
'group_id' => ':23015',
'job_count' => '10',
'order_id' => '139370',
'credits_used' => '100.45'
}
};
foreach my $key (keys %{$job}) {
print "key=$key|value=$job->{$key}\n";
# Testing if "$job->{$key}" is a HASH ref
# ...if yes, we iterate inside the HASH
# through the next level.
if (ref($job->{$key}) eq "HASH") {
foreach my $key2 (keys %{$job->{$key}}) {
print "\tkey=$key2|value=$job->{$key}->{$key2}\n";
}
}
}
这是输出:
key=opstat|value=ok
key=response|value=HASH(0x1638998)
key=currency|value=USD
key=group_id|value=:23015
key=order_id|value=139370
key=job_count|value=10
key=credits_used|value=100.45
如果您想访问“group_id”键:
print $job->{response}->{group_id};
如果您只想访问“响应”哈希而不测试任何内容:
foreach my $key (keys %{$job->{response}}) {
print "key=$key|value=$job->{response}->{$key}\n";
}
或使用此while
循环和each
:
while (my ($key,$value) = each %{$job->{response}}){
print "key=$key|value=$value\n";
}