[tpm] dereferencing anonymous hashes

Shaun Fryer sfryer at sourcery.ca
Tue Apr 10 13:49:48 PDT 2007


Sorry for innundating you with emails Fulko. :)

Perhaps of more value to consider (for those who don't know), is *why*
to use a reference versus an ordinary string/array/hash/whatever.
Consider this...

my %big_hash = ( ... );

$big_hash{foo} = 1;

# this makes a *totally seperate copy* of %big_hash in memory
my %copy_of_big_hash = %big_hash;

$copy_of_big_hash{foo} = 2;

# at this point $big_hash{foo} still equals 1

# this makes a reference pointing to the memory address where %big_hash is stored
my $ref_to_big_hash = \%big_hash;

$ref_to_big_hash->{foo} = 3;

# now $big_hash{foo} equals 3, but $copy_of_big_hash{foo} still equals 2

my $copy_of_ref_to_big_hash = $ref_to_big_hash;

$copy_of_ref_to_big_hash->{foo} = 4;

# now $big_hash{foo} equals 4, but $copy_of_big_hash{foo} still equals 2

Does that make sense? The same principal holds for array refs, blessed objects
and any other sort of "reference versus copy" situation.
--
    Shaun Fryer
    tf: 866-920-9209

On Tue, Apr 10, 2007 at 04:29:25PM -0400, Shaun Fryer wrote:
> # ah yes .. and I forgot the actual question. lol
> 
> %x = ( this => that );
> 
> # the value of 'this' can be obtained by doing this
> 
> $y = $x{this};
> 
> # howver as a hash reference...
> 
> $x = { this => that };
> 
> $y = $x->{this}; # you must use a 'pointer' to dereference the value
>
> On Tue, Apr 10, 2007 at 04:23:27PM -0400, Shaun Fryer wrote:
> > On Tue, Apr 10, 2007 at 02:58:33PM -0400, Fulko Hew wrote:
> > > It makes me wonder then... whats the subtle difference
> > > between
> > > $x = () and $x = {} when dealing with hashes and their references?
> > 
> > @x = (); # this is an array
> > %x = (); # this is an array, in hash context
> > $x = \@x; # this is a reference to an array
> > $x = \%x; # this is a reference to a hash
> > $x = []; # this is a reference to an array
> > $x = {}; # this is a reference to a hash
> > 
> > So one might do this...
> > 
> > @x = qw( three element array );
> > $x = \@x;


More information about the toronto-pm mailing list