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

Why the following code does not work :
use Devel::Pointer; my %hash; $hash{1} = 2; my $code = &create(\%hash); print "CODE : ".$code."\n"; my $ref = &extract($code); print "REF : ".$ref."\n"; sub create { my $self = shift; return(address_of($self)); } sub extract { my $self = shift; return(deref($self)); }
Another question is why each time I use the address_of method the return value is different for the same reference. Is there a way to decode this value so I can use it as an hash key ?

Replies are listed 'Best First'.
Re: How do I use Devel::Pointer in different scopes ?
by broquaint (Abbot) on Mar 31, 2002 at 14:25 UTC
    In &create() you get the address of the value in $hash{1}, which is only available within that scope. So when you try and dereference it in &extract() perl breaks because you're trying to dereference a non-existant value.
    However if you directly pass address_of() $hash{1}, you'll get the expected reference. So this code will work
    use strict; use Devel::Pointer; my %hash; $hash{foo} = "bar"; my $ref = address_of($hash{foo}); print "reference : ".$ref."\n"; my $val = deref($ref); print "value : ".$val."\n"; __output___ reference : 9900396 value : bar
    The reason why you get a different reference value from address_of() each time is because you're creating a new scope, and a new value, so the reference will always be different.
    I really wouldn't recommend using Devel::Pointer for day-to-day reference munging (hence the Devel), you ain't using C no more kid ;-) For some authoritative information on references in perl check out perlref.
    HTH

    broquaint