More Hash problems

Curtis Poe cp at
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

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

  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.


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.


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.


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:


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
      $key = shift @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?

Curtis Poe
Senior Programmer
ONSITE! Technology, Inc.

Taking e-Business and Internet Technology To The Extreme!


More information about the Pdx-pm-list mailing list