More Hash problems

Colin Kuskie ckuskie at
Wed Jun 5 16:26:59 CDT 2002

On Wed, Jun 05, 2002 at 01:39:36PM -0700, Jason White wrote:
> I'm having some trouble with the contents of my hash changing.
> I start with a numerically keyed list of arrays.  The first element of each array is a name.
> The goal is to have one hash of rules indexable by integer keys and another indexable by name.
> Here is my code:
1: my (%rules) = blah blah blah;  #Works and indexes fine
2: while(($key,$value)=each(%rules)){
3:     ($key,@{$value})=@{$value};
4:     $RULES{$key}=$value;
5: }

I think you're a victim of aliasing.  You see, here's what your code
really does:

1: Assign stuff to hash
2: take each key and a reference to the value from the hash
3: modify the actual contents of the hash value via the reference
   ($key, @{ $value }) = @{ $value };
4: create the new hash key/value pair.

There are several screwy things going on:

1) in the each, you never use the key!  Use values with a for loop instead.

foreach $v ( values(%hash) ) {

2) Don't recycle variables names carelessly.  If you'd used a
different variable name for the array for the 2nd hash, it would
work okay.

I tried this and it works:

my ($key, $v);
my %HASH;
my @arr;

foreach $v ( values(%hash) ) {
  @arr = @{ $v };
  $key = shift @arr;
  $HASH{$key} = \@arr;


More information about the Pdx-pm-list mailing list