取消引用perl中的嵌套散列 [英] dereferencing a nested hash in perl

查看:161
本文介绍了取消引用perl中的嵌套散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #!/ usr / bin / perl 

use strict;
使用警告;

my%ani_hash =(
'machine_results'=> [
{
'status'=>'安装失败,
'机器= '23.73.134.235',
'秒'=>'20',
'尝试'=>'1'
},
{
'status'=>'安装失败',
'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;
打印%hashref1\\\
;

foreach我的$ machineresult(键%hashref2){
foreach我的$ machineresult2(键%{$ hashref2 {$ machineresult}}){
print$ hashref2 {$ machineresult } {$ machineresult2} \\\
;
}
}
}

输出:

HASH(0x1e9fe58)
不是./hashref处的HASH参考。 pl line 62.
在使用./hashref.pl第62行的strict refs时,不能使用字符串(MC-5897)作为HASH ref。

我想遍历所有键值对并获取它们的值。
我不想使用自卸车方法来获取值,我想通过循环方法来获取这些值。任何帮助,将不胜感激。谢谢



我这样做是为了解决这个问题并获得'machine_results'的内容。

  printdescription:$ hashref2 {description} \\\
;

foreach my $ machineresult(sort keys%hashref2){
foreach my $ array(@ {$ hashref2 {$ machineresult}}){
foreach my $ array1(sort keys %{$ array}){
printkey是$ array1,它的值是$ array-> {$ array1}`,
在这里输入代码`\\\
;
}
打印\\\
;


$ / code $ / pre

解决方案

代码没有正确解开嵌套散列。对于散列%h =('key'=> [1,2])键相关的值是一个(匿名)数组的引用,所以是一个标量。请参阅最后的链接。

要获得数组的内容,我们需要去引用它。然后这些数组元素本身就是hashrefs,它们也需要被去引用。

  sub get_elements 
{
my%hash =%{$ _ [0]};
print描述:$ hash {'description'} \\\
;
foreach my $ mach_res(keys%hash)
{
next $ mach_res eq'description';
foreach my $ elem(@ {$ hash {$ mach_res}}){
my%mach_detail =%$ elem;
打印\ t --- \\\
;
foreach my $ key(sort keys%mach_detail){
print\t $ key => $ mach_detail {$ key} \;
}
}
}
}

hashref用于获取新的'in-sub'副本%hash 。这是对错误的一些保护,因为原始数据无法更改。但是如果你希望subs直接改变他们得到引用的数据,那么你需要使用引用本身。这打印

 
描述:MC-5897
---
machine => 23.73.134.235
秒=> 20
status =>安装失败
尝试=> 1
---
机器=> 23.73.134.140
秒=> 20
status =>安装失败
try => 1

代码将处理除'description'以外的任何其他键。如果您想要对齐打印输出,您可以首先拉取一个关键字(单词)的最大长度,然后使用 printf 获取详细信息。

 使用List :: Util qw(max); 
foreach my $ elem(@ {$ hash {$ mach_res}}){
my%mach_detail =%$ elem;
my $ max_len = max(地图{长度}键%mach_detail);
打印\ t --- \\\
;
foreach我的$ key(排序键%mach_detail){
#print\ t $ key => $ mach_detail {$ key} \;
printf(\t%$ {max_len} s =>%s\\\
,$ key,$ mach_detail {$ key});


模块 List :: Util 用于获取 max 函数。

 
描述:MC-5897
---
machine => 23.73.134.235
秒=> 20
status =>安装失败
尝试=> 1
---
机器=> 23.73.134.140
秒=> 20
status =>安装失败
try => 1






相关最近的SO资源:嵌套散列/数组哈希数组


#!/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.

I want to loop through all the key value pairs and get their values. I don't want to use the dumper method to get the values, I want to get these by looping method. Any help would be appreciated. Thanks

I did this to fix the issue and get the contents of '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";
    }
}

解决方案

Your code is not unpacking the nested hash correctly. For a hash %h = ('key' => [1, 2]) the value associated with key is a reference to an (anonymous) array, so a scalar. See links at the end.

To get to the content of the array we need to de-reference it. Then those array elements are hashrefs themselves and they need to be de-referenced as well

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";
            }   
        }           
    }   
}

The hashref is used to get a new 'in-sub' copy %hash. This is some protection from errors, since the original data cannot be changed. But if you want subs to directly change data whose reference they get then you need to work with the reference itself. This prints

description: MC-5897
        ---
        machine => 23.73.134.235
        seconds => 20
        status => Failed install
        try => 1
        ---
        machine => 23.73.134.140
        seconds => 20
        status => Failed install
        try => 1

Code will process any additional keys other than 'description'. If you'd like to align the printout, you can first pull the maximum length of a key (word) in it, then use printf for details.

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 is used to get max function. Now you get

Description: MC-5897
        ---
        machine => 23.73.134.235
        seconds => 20
         status => Failed install
            try => 1
        ---
        machine => 23.73.134.140
        seconds => 20
         status => Failed install
            try => 1


A couple of related recent SO resources: a nested hash/array and an array of hashes.

这篇关于取消引用perl中的嵌套散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆