in reply to Undefined Array Reference

Maybe something like this?

... for my $i (0..$#$ref_a) { push @{$ref_a->[$i]}, @{ ref($ref_b->[$i]) eq 'ARRAY' ? $ref_b->[$i] : [(' ') x 3] }; } print Dumper($ref_a); __END__ $VAR1 = [ [ 'a', 'b', 'c', 'j', 'k', 'l' ], [ 'd', 'e', 'f', 'm', 'n', 'o' ], [ 'g', 'h', 'i', 'p', 'q', 'r' ], [ 'x', 'y', 'z', ' ', ' ', ' ' ], [ '3', '4', '5', ' ', ' ', ' ' ], [ '6', '7', '9', ' ', ' ', ' ' ] ];

... my interpretation of the "space in the $ref_b"  :)

Replies are listed 'Best First'.
Re^2: Undefined Array Reference
by wol (Hermit) on Apr 23, 2009 at 16:05 UTC
    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();