in reply to Replace Hash-Ref with Array-Ref
Technique, the first: we just assign a new reference to $ref, so that the pointer is pointing to the baz array.
use Data::Dumper; my $VAR1 = { "baz" => [1,2,3,4] }; my $VAR2 = $VAR1; print "BEFORE\n", Dumper($VAR1, $VAR2); # Note $VAR1 is changed, but $VAR2 is still the hashref. replace_ref($VAR1); print "AFTER\n", Dumper($VAR1, $VAR2); sub replace_ref { $_[0] = $_[0]{baz}; }
Technique, the second: we actually swap the hash and array around in memory. This swaps all references to them!
use Data::Dumper; use Data::Swap; my $VAR1 = { "baz" => [1,2,3,4] }; my $VAR2 = $VAR1; print "BEFORE\n", Dumper($VAR1, $VAR2); # Note that both $VAR1 and $VAR2 are changed. replace_ref($VAR1); print "AFTER\n", Dumper($VAR1, $VAR2); sub replace_ref { swap $_[0], $_[0]{baz}; }
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Replace Hash-Ref with Array-Ref
by Anonymous Monk on Nov 08, 2012 at 09:57 UTC | |
by Anonymous Monk on Nov 11, 2012 at 08:00 UTC |
In Section
Seekers of Perl Wisdom