More Hash problems

Tom Phoenix rb-pdx-pm at
Wed Jun 5 16:38:20 CDT 2002

On Wed, 5 Jun 2002, Jason White wrote:

> I'm having some trouble with the contents of my hash changing.

Well, the contents are being changed by you, me, or Santa Claus. I'll let
you narrow that down. :-)

> 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.

"Indexable by integer keys" sounds like "a job for an array", doesn't it?

> Here is my code:
> my (%rules) = blah blah blah;  #Works and indexes fine

There's no extra charge for writing your code like this:

    my(%rules) = qw{ fred 210   barney 170   dino 30 };	# or whatever...

...and it has the added benefit that we can see more about what you're
doing, and thereby offer more (and better) help.

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

Isn't that just the hard way to write this?

    $key = shift @$value;

Not only the hard way to write it, but it's more work for Perl. (Less
efficient.) And why are you reusing $key here? That's just confusing. If
you don't care what the keys are, use a foreach loop on values(%rules),
since that will be clearer to your maintenance programmer. Or at least,
use two different variables for two different things. Variables are cheap;
use all you need.

>     $RULES{$key}=$value;
> }

So, where are the numbers? You've built a new hash (presuming that %RULES
was empty before you started), but I can't see that either one is keyed by
number. Unless %rules was set up that way at the start, but you didn't
show its real data to us. (Hint, hint. :-)

> Now %RULES Works and indexes fine with the names as keys but the first
> element of my arrays are gone in the first hash.

And in %RULES, too, of course. Ah, I thought that that was a shift. Maybe
you wanted something like this?

    my $second_key = $value->[0];

> I also tried adding %TmpHash=%rules and then parsing the %TmpHash, but
> it still affected %rules.

That's because it's not a "deep copy". Copying a reference gives you a
copy of a reference, not a new reference pointing to a copy of the data.
(But if you really want a deep copy, that's possible. Finding the correct
module on CPAN is left as an exercise for the ambitious student.)

I hope this gets you back on the right track. Good luck with it!



More information about the Pdx-pm-list mailing list