nega has asked for the wisdom of the Perl Monks concerning the following question:

I have some hashes that look like:
my (%hash1, %hash2, %hash3); my %hash_names = ( "%hash1" => "Hash One", "%hash2" => "Hash Two", "%hash3" => "Hash Three" );
I also have a subroutine that I would call like this:
&subroutine(\%hash1, "Hash One");
I would like to call it like:
foreach $key (sort keys %hash_names) { &subroutine($key, $hash_names{$key}); }
but I cant seem to work it out. Any pointers?

nega

Replies are listed 'Best First'.
Re: Using a hash key as another hash's name...
by merlyn (Sage) on Sep 03, 2000 at 04:28 UTC
    That's almost never a good idea. What you want is to use a hash of hashrefs, then key off that.
    my %data; $data{"hash1"} = \%hash1; $data{"hash2"} = \%hash2; $data{"hash3"} = \%hash3; ... for (sort keys %data) { subroutine($_, $data{$_}); }
    The subroutine will see the hashref, so dereference it to get at the rest of the data. And if you really don't need %hash1 by name then, even simpler!
    my %data; $data{"hash1"} = { key1 => 25, key2 => 19, ... }; $data{"hash2"} = { key5 => 12, key8 => 'hi', ... }; $data{"hash3"} = { fred => 'flintstone', barney => 'rubble' };
    See perllol and perldsc and perlref for more info.

    -- Randal L. Schwartz, Perl hacker

      Came in tonight to pick up my laptop so I could bring this monster back to the couch im living on and work on it overnight. My post and your reply were still up on my monitor and I took a quick look at both and suddenly realized what I was doing wrong and what exactly your reply meant. So I swapped my keys and values, stopped refering to the new 'value' as a string, and swapped $_ and $data{$_} in the subroutine call and everything was perfect. Guess I just needed another set of eyes. Thanks!