http://www.perlmonks.org?node_id=1015336

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

my @array = qw(var1 var2 var3); foreach my $element (@array){ #- I want to create my %var1, my %var2, my %var3 #- Is it possible? }
  • Comment on Can I create hash dynamically by looping through an array? The hash name should be the array element
  • Download Code

Replies are listed 'Best First'.
Re: Can I create hash dynamically by looping through an array? The hash name should be the array element
by choroba (Cardinal) on Jan 25, 2013 at 12:51 UTC
    Yes, you can - if you are not using strict refs:
    for my $element (qw/var1 var2 var3/) { %$element = ( a => 'b'); } print $var1{a};
    The common practice, though, is to use one hash instead, making the elements of the list the keys. You can then shorten the creation to
    my @array = qw(var1 var2 var3); my %hash; undef @hash{@array};
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Can I create hash dynamically by looping through an array? The hash name should be the array element
by AnomalousMonk (Archbishop) on Jan 25, 2013 at 13:31 UTC
Re: Can I create hash dynamically by looping through an array? The hash name should be the array element
by toolic (Bishop) on Jan 25, 2013 at 13:16 UTC
Re: Can I create hash dynamically by looping through an array? The hash name should be the array element
by Anonymous Monk on Jan 25, 2013 at 12:50 UTC
    Are you quite certain you don't really want a Hash of Hashes?
      Record another vote for a hash of hashes.
      #!/usr/bin/perl -w use strict; print "Content-type:text/html\n\n"; my @array = qw(var1 var2 var3); my %HoH = (); my $i = 0; foreach my $element (@array){ $i++; $HoH{$element} = { 'key'.$i.'1', 'value'.$i.'1', 'key'.$i.'2', 'va +lue'.$i.'2', 'key'.$i.'3', 'value'.$i.'3' }; } foreach my $key1 (sort keys %HoH){ foreach my $key2 (sort keys %{ $HoH{$key1} }){ print "<br>$key1 > $key2 > $HoH{$key1}{$key2}\n"; } }
      Output:
      var1 > key11 > value11 var1 > key12 > value12 var1 > key13 > value13 var2 > key21 > value21 var2 > key22 > value22 var2 > key23 > value23 var3 > key31 > value31 var3 > key32 > value32 var3 > key33 > value33



      Time flies like an arrow. Fruit flies like a banana.