More Hash problems

Curtis Poe cp at onsitetech.com
Wed Jun 5 16:16:51 CDT 2002


I'm having some trouble figure out what you are trying to do.

Here's your code:

  my (%rules) = blah blah blah;  #Works and indexes fine
  while(($key,$value)=each(%rules)){
      ($key,@{$value})=@{$value};
      $RULES{$key}=$value;
  }

Let's walk through this step-by-step.  Explanation is after the line of
code.

  my (%rules) = blah blah blah;  #Works and indexes fine

Okay, that's fine, though you don't need the parens around %rules, but they
don't hurt.

  while(($key,$value)=each(%rules)){

That's syntactically correct.  However, I would declare the $key and $value
with 'my':

  while ( my ( $key, $value ) = each %rules ) {

That doesn't change how this snippet runs, but it means that they won't
exist outside fo the while loop.  Later, if you refer to $key or $value, you
won't have to worry about whether or not they still have a value from the
while loop.

    ($key,@{$value})=@{$value};

Ugh.  This made my brain hurt.  What this does is assign the first scalar in
the $value arrayref to $key and puts the rest of the values in $value.  I
think this would be clearer:

    $key = shift @$value;

Of course, that overwrites the key, which may not be what you want.

    $RULES{$key}=$value;

You have $RULES in upper-case.  Is that what you intended?  You're copying
these values to a different hash.

Now, what I think might be your problem is when you do this:

  while(($key,$value)=each(%rules)){
      ($key,@{$value})=@{$value};

Since $value is a reference to an array, if you change the underlying array,
you're changing the value of $value, including in the original array.  If
that's your problem, and if you really mean to write this to another hash,
here's what I would do:

  my %rules = blah blah blah;  #Works and indexes fine
  while( my ($key,$value) = each %rules) {
      my @values = @$value; # this will copy the data without changing
$value
      $key = shift @values;
      $RULES{$key}=\@values;
  }

What I did was copy the values from the array reference to an actual array.
With that, you can alter the new array all you want without affecting the
original array.  The new rules hash will have keys equal to the first value
in that array, and the values will be an array reference of the original
array values, minus the first element (which was shifted off).

Does that make sense, or did I miss the boat?

--
Cheers,
Curtis Poe
Senior Programmer
ONSITE! Technology, Inc.
www.onsitetech.com
503-233-1418

Taking e-Business and Internet Technology To The Extreme!

TIMTOWTDI



More information about the Pdx-pm-list mailing list