Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Can I create hash dynamically by looping through an array? The hash name should be the array element

by tomishere (Novice)
on Jan 25, 2013 at 12:38 UTC ( #1015336=perlquestion: print w/ replies, xml ) Need Help??
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
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.
Re: Can I create hash dynamically by looping through an array? The hash name should be the array element
by choroba (Abbot) 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 toolic (Chancellor) 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 AnomalousMonk (Abbot) on Jan 25, 2013 at 13:31 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1015336]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2014-12-19 14:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (84 votes), past polls