perl: loop over function that returns array or undef -
i looking proper perl-ism issue. can work around have ask...
i using html::treebuilder , using look_down
method. returns array or scalar depending on context , returns undef
if no matching tag found. cool.
i want following:
foreach $tag ( @{ $head->look_down('_tag', 'link') } ) { ... }
but if there no link
tag function returns undef
, generates error can't use undefined value array reference @ mycgi.cgi line ###
. try modification:
foreach $tag ( @{ $head->look_down('_tag', 'link') || [] } ) { ... }
my thought if method returns undef
changed empty array. works when there no link
tags. but, if there @ least 1 expected tag there error: not array reference @ mycgi.cgi line ###
.
do need bite bullet , break method call out of loop , check undef
before entering loop?
"returns array" mentioned in documentation incorrect; perl subroutines return lists (though in scalar context list 1 element).
it not return undef in list context, returns empty list (return
no arguments returns empty list in list context , undef in scalar context). can loop on returned values no @{ }
required:
foreach $tag ( $head->look_down('_tag', 'link') ) { ... }
Comments
Post a Comment