#!/usr/bin/perl
use strict;
use warnings;
my %ani_hash = (
'machine_results' => [
{
'status' => 'Failed install',
'machine' => '23.73.134.235',
'seconds' => '20',
'try' => '1'
},
{
'status' => 'Failed install',
'machine' => '23.73.134.140',
'seconds' => '20',
'try' => '1'
}
],
'description' => 'MC-5897'
);
get_elements( \%ani_hash );
sub get_elements
{
my $hashref1 = shift;
my %hashref2 = %$hashref1;
print "%hashref1\n";
foreach my $machineresult ( keys %hashref2 ) {
foreach my $machineresult2 ( keys %{ $hashref2{$machineresult} } ) {
print "$hashref2{$machineresult}{$machineresult2}\n";
}
}
}
Output:
HASH(0x1e9fe58)
Not a HASH reference at ./hashref.pl line 62.
Can't use string ("MC-5897") as a HASH ref while "strict refs" in use at ./hashref.pl line 62.
我想遍历所有键值对并获取它们的值。我不想使用dumper方法来获取值,我想通过循环方法来获取这些值。任何帮助,将不胜感激。谢谢
我这样做是为了解决问题并获取“ machine_results”的内容。
print "description: $hashref2{description}\n";
foreach my $machineresult( sort keys%hashref2){
foreach my $array (@{ $hashref2{$machineresult} }){
foreach my $array1( sort keys%{$array} ){
print "key is $array1 and it's value is $array->{$array1}`",
"enter code here`\n";
}
print "\n";
}
}
您的代码无法正确解压缩嵌套哈希。对于哈希%h = ('key' => [1, 2])
,与之关联的值key
是对(匿名)数组的引用,因此是标量。请参阅最后的链接。
为了获得数组的内容,我们需要取消引用它。然后这些数组元素本身就是hashrefs,因此也需要取消引用
sub get_elements
{
my %hash = %{ $_[0] };
print "description: $hash{'description'}\n";
foreach my $mach_res (keys %hash)
{
next if $mach_res eq 'description';
foreach my $elem ( @{$hash{$mach_res}} ) {
my %mach_detail = %$elem;
print "\t---\n";
foreach my $key (sort keys %mach_detail) {
print "\t$key => $mach_detail{$key}\n";
}
}
}
}
hashref用于获取新的“子内”副本%hash
。这是防止错误的某种保护,因为原始数据无法更改。但是,如果您希望潜艇直接更改其引用的数据,则需要使用引用本身。此打印
说明:MC-5897 --- 机器=> 23.73.134.235 秒=> 20 状态=>安装失败 尝试=> 1 --- 机器=> 23.73.134.140 秒=> 20 状态=>安装失败 尝试=> 1
代码将处理除“描述”以外的任何其他键。如果要对齐打印输出,可以先拉出其中一个键(单词)的最大长度,然后再使用printf
以获取详细信息。
use List::Util qw(max);
foreach my $elem ( @{$hash{$mach_res}} ) {
my %mach_detail = %$elem;
my $max_len = max( map { length } keys %mach_detail );
print "\t---\n";
foreach my $key (sort keys %mach_detail) {
#print "\t$key => $mach_detail{$key}\n";
printf("\t%${max_len}s => %s\n", $key, $mach_detail{$key});
}
}
Module List :: Util用于获取max
功能。现在你得到
品名:MC-5897 --- 机器=> 23.73.134.235 秒=> 20 状态=>安装失败 尝试=> 1 --- 机器=> 23.73.134.140 秒=> 20 状态=>安装失败 尝试=> 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句