APM: Dereferencing question

Ren Maddox renm at iname.com
Wed Nov 27 07:22:07 CST 2002


On Wed, 2002-11-27 at 00:45, Goldilox wrote:
> If I add a pair to a hash (or several pairs in my case) where the value is a
> reference to an array:
> my %hash;
> $key="thislist";
> @values=qw(Item1 Item2 Item3);
> $hash{$key}=\@values;

Warning:  this construct assigns a reference to the *same* @values for
each key, if this code is executed more than once -- in a loop, for
example.  Making @values a lexical (my) within the loop is one way to
avoid that problem.  (The manifestation of the problem is that all of
the hash values will be the same array reference, and the array will
only have the most recently assigned values.)

> how do I dereference @values?
> 
> foreach $key(keys %hash){
> print "\$key=$key\n";
> print "\@values=??\n";
> }

You want:  print "\@values=@{$hash{$key}}\n"

Though you may find a better construct for this is:

while ( my($key, $value) = each %hash ) {
  print "\$key = $key\n";
  print "\@values = @$value\n";
}

> I need to associate a list for each key. I am unaccustomed to using references
> so feel free to set me straight :0)

Have a(nother?) read through perlreftut(1) -- it does a good job of
explaining most of what is needed to use references.

-- 
Ren Maddox <renm at iname.com>
-- 
Ren Maddox <renm at iname.com>




More information about the Austin mailing list