http://www.perlmonks.org?node_id=1002844


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

    Thanks! Technique, the first was exactly what I was looking for.

    I think I'll read a bit more about @_.

      Mind you, it's far from kosher to have functions that mess with its arguments. You save, what, five characters each function call? Try to do it how brx suggested.

      sub bazify { my ($bar) = @_; return $bar->{baz}; } $ref = bazify($ref);