in reply to Pushing Arrays into Hash without nesting

Hi,

At the top of your script you have

my @array = (10 .. 12); $source{'data'} = \@array;
... and then in the sub in question you have effectively
$data = 'data'; # via arg my @array = $source{$data} ; return @array;

First of all, why attempt to pass the array as a list? In general it's better to pass references around, like the one you stored in the hash. Just return the reference, and let the caller dereference and handle the list. You can dereference the result of the subroutine call, like this:

push (@{ $hash{foo}{bar} }, @{ addSomeNumbersFromSource("data") });

Hope this helps!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Pushing Arrays into Hash without nesting (updated)
by AnomalousMonk (Archbishop) on Feb 13, 2021 at 23:51 UTC
    push (@{ $hash{foo}{bar} }, @{ addSomeNumbersFromSource("data") });

    If addSomeNumbersFromSource() is not changed from the OPed code, then the
        return @array;
    statement will be evaluated in scalar context (dereferencing a scalar array reference) and will return the number of elements in @array.

    tybalt89 has it right for the given code:
       push (@ { $hash{"foo"}{"bar"} } , @{ (addSomeNumbersFromSource("data"))[0] } );

    Update:

    Just return the reference, and let the caller dereference and handle the list.
    Hmmm... On reading 1nickt's reply and re-reading the post to which I was replying, I must admit that that post urged a significant change to the function interface, for which the suggested expression invoking the function was perfectly appropriate. Paying attention to what's written can sometimes be useful. :)


    Give a man a fish:  <%-{-{-{-<

      Hm, yes, I did say "Just return the reference, and ...", in fact my whole point was that the subroutine should not return what the OP posted.


      The way forward always starts with a minimal test.