Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Pushing Arrays into Hash without nesting

by 1nickt (Canon)
on Feb 13, 2021 at 20:37 UTC ( [id://11128347]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-25 22:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found