Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Replace Hash-Ref with Array-Ref

by tobyink (Abbot)
on Nov 08, 2012 at 09:05 UTC ( #1002844=note: print w/ replies, xml ) Need Help??


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'


Comment on Re: Replace Hash-Ref with Array-Ref
Select or Download Code
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);

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2014-08-01 22:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Who would be the most fun to work for?















    Results (50 votes), past polls