Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^2: Undefined Array Reference

by wol (Hermit)
on Apr 23, 2009 at 16:05 UTC ( [id://759576]=note: print w/replies, xml ) Need Help??


in reply to Re: Undefined Array Reference
in thread Undefined Array Reference

Another interpretation would be "when ref_b runs out of data, don't do anything more to ref_a".

If this is what's needed then:

for my $i (0..$#$ref_a) { push @{$ref_a->[$i]}, @{$ref_b->[$i] || []}; }
Ie, if @{$ref_b} hasn't got as many members as @{$ref_a}, then at some point $ref_b->[$i] is undef, so dereference a reference to an empty array in that case.

(I also tried to use || last there (ie exit the loop early) but that comes up with a "bizarre" error message.)

If it's also possible for ref_b to have more members than ref_a, and the extras should be tacked on verbatim, then the range of the for loop needs to be adjusted to cover them. Here's one option which is moderately readable:

for my $i (0.. ($#$ref_a > $#$ref_b ? $#$ref_a : $#$ref_b) ) {
Handily, extra elements appear in ref_a automatically as needed, so there's no need for a || [] on the first argument to push.

Update: Re-reading the thread made me realise that because of the autovivification in ref_a, ikegami's suggestion does acheive all this (I think) but much more subtly. Too subtle for me the first time round ;-)

--
use JAPH;
print JAPH::asString();

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://759576]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-25 14:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found