Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Pass by value acts like pass by reference

by davido (Cardinal)
on Jul 11, 2004 at 16:22 UTC ( #373472=note: print w/replies, xml ) Need Help??


in reply to Pass by value acts like pass by reference

This is happening because you're passing the keys/values of the hash into push_1() instead of a reference to the hash.

When you pass a hash like this: push_1(%hash), the hash is being flattened into a list of key/value pairs, and they're being assigned into @_. You should be passing the hash like this: push_1(\%hash), and then properly dereferencing it like this within the sub:

my $href = shift; for my $key ( keys %{ $href } ) { push @{$href->{$key}}, 1; }

Hope this helps...

Update: Oh shoot, this is a botched answer. In testing and tinkering with your script I see that, as expected, the hash inside the sub is a different one than the one outside the sub, and in deparsing the code I see that as you pass the hash, it's being passed as a flattened list. So I can't explain the behavior you've identified.

Update 2: Duh, how blind could I be? Thanks tilly for spelling it out here (and reminding me in CB): The value of each hash element, in your example, is an arrayref, and that value passes unchanged into the subroutine. That means that you can dereference the value held in the lexical hash within the sub just as you would the value of the lexical hash outside the sub; they're different hashes, but their values hold references to the same anonymous arrays.


Dave

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2023-01-31 10:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?