如何使用XML :: Simple处理未定义的引用? [英] How should I handle undefined references with XML::Simple?

查看:181
本文介绍了如何使用XML :: Simple处理未定义的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这些选项解析XML文件XML :: Simple

I'm parsing a XML file with XML::Simple using these options

my $xml = XML::Simple->new(ForceArray => 1, KeyAttr => 1, KeepRoot => 1);

这是一个示例xml文档

This is a sample xml document

<ip>
    <hostname>foo</hostname>
    <info>server</info>
    <soluton>N/A</solution>
    <cats>
        <cat>
            <title>Baz</title>
            <flags>0</flags>
        </cat>
        <cat><title>FooBar</title></cat>
    </cats>
</ip>
<ip>
    <info>client</info>
    <diagnosis>N/A</diagnosis>
    <cats>
        <cat><title>Foo</title></cat>
        <cat>
            <title>Bar</title>
            <update>Date</update>
        </cat>
    </cats>
</ip>

正如你所看到的,并不是每个节点都有hostname属性,这导致我的脚本死了当我尝试获取主机名时,无法使用未定义的值作为ARRAY引用错误

As you can see, not every node has the hostname attribute, which causes my script to die with an "Can't use an undefined value as an ARRAY reference" error when I try to get the hostname

   $nb = "@{ $_->{hostname} }";

xml中有几个可选元素(十几个)。该怎么处理?
我应该在作业之前检查元素的存在吗?

There are several optional elements in the xml (more than a dozen). How should I handle that? Should I check the existence of the element prior to the assignment?

if ( @{ $_->{hostname} ) { $nb = "@{ $_->{hostname} }" }
if ( @{ $_->{solution} ) { $s  = "@{ $_->{solution} }" }
if ( @{ $_->{diagnosis} ) {...}

我应该使用eval块吗?

Should I use an eval block?

eval { $nb = "@{ $_->{hostname} }" };

也许

eval {
    $nb = "@{ $_->{hostname} }";
    $s  = "@{ $_->{solution} }";
    $d  = "@{ $_->{diagnosis} }";
};

有没有更好的方法?

推荐答案

首先,你真的需要启用ForceArray选项吗?也许最好使用标量值并检查它们(可能)的数组?

First at all, do you really need 'ForceArray' option enabled? Maybe it's better to use scalar values and check for arrays where they (possible) are?

我使用的可能是未定义的数组引用的解决方案是: / p>

Solutions for references to array that-may-be-undefined I use is:

my $string = join '', @{ $var || [] };

这意味着取消引用变量或空的匿名arrayref。

Which means "dereference variable or empty anonymous arrayref".

在你的情况下,这将是

$nb = join '', @{ $_->{hostname} || [] };

这篇关于如何使用XML :: Simple处理未定义的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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