1

I am looking for the proper perl-ism for this issue. I can work around it but just have to ask...

I am using HTML::TreeBuilder and am using the look_down method. This returns an array or scalar depending on context and returns undef if no matching tag is found. Cool.

I want to do the following:

foreach my $tag ( @{ $head->look_down('_tag', 'link') } ) {
    ...
}

but if there is no link tag the function returns undef and generates the error Can't use an undefined value as an ARRAY reference at myCGI.cgi line ###. So I try this modification:

foreach my $tag ( @{ $head->look_down('_tag', 'link') || [] } ) {
    ...
}

My thought was that if the method returns undef then it will get changed into an empty array. This works when there are no link tags. But, if there is at least one expected tag then there is an error: Not an ARRAY reference at myCGI.cgi line ###.

Do I need to just bite the bullet and break the method call out of the loop and check for undef before entering the loop?

0

1 Answer 1

3

"returns an array" is sometimes mentioned in documentation but is incorrect; perl subroutines always return lists (though in scalar context it will be a list with only one element).

It does not return undef in list context, it returns an empty list (return with no arguments returns an empty list in list context and undef in scalar context). You can just loop over the returned values with no @{ } required:

foreach my $tag ( $head->look_down('_tag', 'link') ) {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.