无法访问使用XML解析器创建的数组元素的哈希值

时间:2012-06-20 10:33:24

标签: perl

我的XML Parser如下所示:

$VAR1 = {
    'Symmetrix' => {
        'Masking_View' => {
            'View_Info' => {
                'Initiators' => {
                    'user_node_name' => [
                        '5001438001725614',
                        '5001438001725714'
                    ],
                    'user_port_name' => [
                        '5001438001725614',
                        '5001438001725714'
                    ],
                    'wwn' => [
                        '5001438001725614',
                        '5001438001725714'
                    ]
                },
                'port_grpname' => 'PG_1E0_2E0'
            }
        },
        'Symm_Info' => {
            'symid' => '000295900074'
        }
    }
};

我想拉出wwn的元素。但是我无法通过。

#!C:\Perl\bin

use strict;
use XML::Simple;
use Data::Dumper;

my $input_file = $ARGV[0];
my $detail_info = XMLin("$input_file");

# Loop through each view_info
$detail_info->{Symmetrix}{Masking_View}{View_Info} = [ $detail_info->{Symmetrix}       {Masking_View}{View_Info} ] if ref ($detail_info->{Symmetrix}{Masking_View}{View_Info})   ne 'ARRAY';
foreach my $view_info  (@{$detail_info-> {Symmetrix}{Masking_View}{View_Info}})
{
      $view_info->{Initiators} = [$view_info->{Initiators}] if ref ($view_info->    {Initiators}) ne 'ARRAY';
foreach my $wwn (keys %{$view_info->{Initiators}})
    {
     my @flags = ();
     push (@flags,"$wwn:$view_info->{Initiators}{$wwn}";
     print @flags;
     #"{$wwn->{wwn}}";
    }
}    

我的输出如下;

{ARRAY(0x20c8904)}

我在不同行的单行中寻找wwn元素。

1 个答案:

答案 0 :(得分:1)

您生成了太多代码来区分arrayref值和非参考值。 Strict mode要求您设置ForceArray选项,因此您可以确定每个值都是一个arrayref,即使其中只有一个元素。

use strictures;
use XML::Simple qw(:strict);
my $detail_info = XMLin($ARGV[0], ForceArray => 1, KeyAttr => []);
# $detail_info is {
#     Symmetrix => [
#         {
#             name      => 'Masking_View',
#             View_Info => [
#                 {
#                     Initiators => [
#                         {
#                             user_node_name => [5001438001725614, 5001438001725714],
#                             user_port_name => [5001438001725614, 5001438001725714],
#                             wwn            => [5001438001725614, 5001438001725714]
#                         }
#                     ],
#                     port_grpname => 'PG_1E0_2E0'
#                 }
#             ]
#         },
#         {
#             name  => 'Symm_Info',
#             symid => '000295900074'
#         }
#     ]
# }
my @flags;
for my $view_info (@{ $detail_info->{Symmetrix}[0]{View_Info} }) {
    for my $initiator (@{ $view_info->{Initiators} }) {
        push @flags, $initiator->{wwn};
    }
}
# @flags is (
#     [
#         5001438001725614,
#         5001438001725714
#     ]
# )