The best way to see if there is a child that matches 'get_this' is to try to get it, there is really no need to use 2 methods, one to test if it's there and one to retrieve it. So the loop should look like this:
for my $para ( $root->children('para') ) { if ( my $get_this= $para->first_child('get_this') ) { print $get_this->att('value'), "\n"; } }
The docs for child_matches are a bit... short. In fact child_matches is based on child, which needs an offset as a first argument. Hence the test returned true even for the second para, at which point trying to grab the first_child failed, returning undef.
As a side note, if you had printed a \n after the attribute value, you would have gotten the first 'yes', and then the crash. But because output is buffered, you didn't see it. So it might be a good idea to output a \n (or unbuffer output) when doing tests like this.
In reply to Re: XML::Twig first_child_matches question
by mirod
in thread XML::Twig first_child_matches question
by convenientstore
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |