我试图在Perl中打印一些基本日志,但我遇到了一个非常简单的问题:我无法打印
XML标签的内容.
my $twig=XML::Twig->new(pretty_print => "nice"); $twig->parse($xml); my $root = $twig->root; my @desc=$root->descendants_or_self('node'); my $nrofdesc=@desc; my $sentence = $root->descendants('sentence')->print; my $sentenceid = $root->{att}->{id}; if ($nrofdesc > $maxdescendants) { print "$sentence\t$nrofdesc\t$sentenceid\n"; }
Can’t call method “print” without a package or object reference at
file.pl line 35,line 15.
这是哪一行:
my $sentence = $root->descendants('sentence')->print;
我也尝试过经常提出的文本,但是我得到了同样的错误.我在这里错过了什么?
解决方法
这不是jQuery; – (你必须遍历后代列表.
另外你不能使用print来收集变量中的数据,你使用print来打印!使用sprint代替:
$sentence= join '',map { $_->sprint } $root->descendants('sentence');
如果您想要的是元素的文本,并且所有句子元素的内容都是纯文本,您还可以使用$sentence = $root-> findvalue(‘// sentence’)
此外,使用$root-> att(‘id’)或$root-> id,因为$root-> {att} – > {id}不是官方API的一部分,并且可能会更改未来.