in reply to dynamically creating the name of a hash key-name

I have a related question:

If I want to create 20 separate hashes dynamically, each of which has the same keys but different values, I want to have

$hash$numericid{$key} = $value;
How to get each has to be named
%hash1, %hash2, etc?
-clay
  • Comment on Re: dynamically creating the name of a hash key-name

Replies are listed 'Best First'.
RE: Re: dynamically creating the name of a hash key-name
by arturo (Vicar) on Oct 02, 2000 at 00:53 UTC

    One way to do pretty much what you're asking for relates to a reply above: what you can do is have an array of anonymous hashes, of the form:

    my @array_of_hashes = ( {hashkey1=>$hashval1, hashkey2=>$hashval2}, {hashkey1=>$hashval1, hashkey2=>$hashval2} ... );

    You access the individual hashes with syntax like:

    # to modify what's in the second hash $array_of_hashes[1]->{hashkey1} = "ay carumba!"; # $array_of_hashes[1]{hashkey1} would also work! # to iterate over the hashes foreach my $hashref (@array_of_hashes) { # $hashref is now a reference to one of the hashes in @array _of_hashe +s # we need to de-reference to go through the keys of the hash foreach (keys %$hashref) { print "$_ => ", $hashref->{$_}, "\n"; } }

    HTH

    Philosophy can be made out of anything -- or less

RE: Re: dynamically creating the name of a hash key-name
by Jouke (Curate) on Oct 02, 2000 at 10:14 UTC
    To do this, you would need a piece of code like this:

    #!/usr/bin/perl my ($i, @hasharray, $x); # create an array of hashnames (hash0..hash9) for ($i=0; $i<10; $i++) { push @hasharray, "hash$i"; } $i = 10; foreach (@hasharray) { $x = $_; #assign key "key" and value "value$i" to %hashx $$x{key} = "value$i"; $i++; } print "$hash7{key}\n"; #would print "value17"
    But don't use strict or -w here! Strict would prevent using a string as a hashref ($$x{key} = "value$i") and -w would warn us that %hash7 was used only once...

    So you see, it is possible, but I think it's not wise...

    HTH

    Jouke Visser, Perl 'Adept'