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

Pass by reference question...

by freddo411 (Chaplain)
on Mar 05, 2012 at 18:45 UTC ( [id://957948]=perlquestion: print w/replies, xml ) Need Help??

freddo411 has asked for the wisdom of the Perl Monks concerning the following question:

Considering the test code below, I'm wondering why I can't replace a "passed-by-reference" hashref with another hashref in my sub routine.

$|++; my $href = { one => 1, two => 2 }; print "\nBefore:\n"; print Dumper($href); set_element($href); print "\nset_element:\n"; print Dumper($href); assign_new_href($href); print "\nAttempt to assign new hashref:\n"; print Dumper($href); ########## sub assign_new_href { my $href = shift; $href = { new_key => 4 } ; } ########## sub set_element { my $href = shift; $href->{baz} = 4; }

The output (below) shows that the attempt to assign a new hashref fails silently. ?@#$%?.

Before: $VAR1 = { 'one' => 1, 'two' => 2 }; set_element: $VAR1 = { 'baz' => 4, 'one' => 1, 'two' => 2 }; Attempt to assign new hashref: $VAR1 = { 'baz' => 4, 'one' => 1, 'two' => 2 };

-------------------------------------
Nothing is too wonderful to be true
-- Michael Faraday

Replies are listed 'Best First'.
Re: Pass by reference question...
by chromatic (Archbishop) on Mar 05, 2012 at 18:57 UTC
    The output (below) shows that the attempt to assign a new hashref fails silently.

    No, it works:

    sub assign_new_href { my $href = shift; $href = { new_key => 4 } ; }

    Within that function, you do assign a new hash reference to the lexical $href. However it doesn't modify the hash to which $href refers because that's not how references work. Think of $href as a container. You've dumped out its contents to replace those contents with something else. What you want to do is replace the contents of its contents with something else:

    sub assign_new_href { my $href = shift; %$href = ( new_key => 4 ); }

    Improve your skills with Modern Perl: the free book.

Re: Pass by reference question...
by JavaFan (Canon) on Mar 05, 2012 at 19:01 UTC
    Because you are making a copy of the reference, and then you modify the copy. Either change the alias, or modify what the reference is pointing to:
    sub assign_new_ref { $_[0] = {new_key => 4}; # Change alias } sub assign_new_ref { my $href = shift; %$href = (new_key => 4); # Change what the reference is pointing t +o }
    Code is untested.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-24 22:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found