为什么我用Perl XML :: Simple得到这个“不是数组引用”?

时间:2022-08-22 22:43:53

My input xml file is:

我输入的xml文件是:

<?xml version='1.0'?>
<warnings>
 <IDA>
  <file>filea</file>
  <path>patha</path>
 </IDA>

 <IDA>
  <file>fileaa</file>
  <path>pathaa</path>
 </IDA>

 <IDB>
  <file>fileb</file>
  <path>pathb</path>
 </IDB>

</warnings>

I am reading this file like this:

我正在读这样的文件:

my @IDs = ("IDA", "IDB");
my $data = $xml->XMLin("xmlfile.xml");
foreach (@IDs)
{
 foreach $id (@{$data->{$_}})
 {
   print $id->{path}."\n";
 }
}

and when I run the script it gives me this error:

当我运行脚本时,它给了我这个错误:

Not an ARRAY reference at ./waiver.pl line 18.

(line 18 is the second foreach loop)

(第18行是第二个foreach循环)

EDIT i have duplicated IDA tag.

编辑我有重复的IDA标签。

1 个解决方案

#1


5  

{$data->{$_} is not a valid array reference because you have only one IDA tag, thus no array is built. You can use ForceArray in XMLin to force every tag to be an array even if there's only one.

{$ data - > {$ _}不是有效的数组引用,因为您只有一个IDA标记,因此不会构建任何数组。您可以在XMLin中使用ForceArray强制每个标记都是一个数组,即使只有一个。

my $data = $xml->XMLin("xmlfile.xml", ForceArray => 1);

EDIT: now it's giving the error with IDB tag...

编辑:现在它给IDB标签的错误...

Alternatively you can use ref() to check if it's an array or a hash reference:

或者,您可以使用ref()来检查它是数组还是哈希引用:

if (ref({$data->{$_}) eq 'ARRAY')
{
    foreach $id (@{$data->{$_}})
    {
        etc...
    }
}

PS: also may I suggest using keys() function to retreive the keys of the hash instead of having them in a separate array.

PS:我也建议使用keys()函数来检索哈希的键,而不是将它们放在一个单独的数组中。

#1


5  

{$data->{$_} is not a valid array reference because you have only one IDA tag, thus no array is built. You can use ForceArray in XMLin to force every tag to be an array even if there's only one.

{$ data - > {$ _}不是有效的数组引用,因为您只有一个IDA标记,因此不会构建任何数组。您可以在XMLin中使用ForceArray强制每个标记都是一个数组,即使只有一个。

my $data = $xml->XMLin("xmlfile.xml", ForceArray => 1);

EDIT: now it's giving the error with IDB tag...

编辑:现在它给IDB标签的错误...

Alternatively you can use ref() to check if it's an array or a hash reference:

或者,您可以使用ref()来检查它是数组还是哈希引用:

if (ref({$data->{$_}) eq 'ARRAY')
{
    foreach $id (@{$data->{$_}})
    {
        etc...
    }
}

PS: also may I suggest using keys() function to retreive the keys of the hash instead of having them in a separate array.

PS:我也建议使用keys()函数来检索哈希的键,而不是将它们放在一个单独的数组中。