Using the names of hashes (or of any other variables) to implement a nested data structure is almost always a bad idea.

Instead, make use of Perl's nested data structures -- they're very easy to use.

Instead of storing the name of a hash in $fields[0] and then going $${fields[$i]}{$j}, you could just as easily create a hash %hash (use a name appropriate to your application instead ;) containing the sub-hashes as values (strictly speaking, it stores references): $hash{$fields[$i]}{$j} is easier to debug because it shows the nature of the nested data structure.

With this in mind, your program looks like this:

my @fields = qw(a b c); my @input = qw( 5.5 3.2 15.0 -22 .02 .15); my %hash; for (my $i=0; $i<=2; $i++) { for (my $j=1; $j<=2; $j++) { $hash{$fields[$i]}{$j} = $input[((2*$i)+$j)-1]; } } for (my $i=0; $i<=2; $i++) { for (my $j=1; $j<=2; $j++) { print $fields[$i] . "{" . $j . "} -> " . $hash{$fields[$i]}{$j}, + "\n +"; } } printf "%.1f\t%.1f\t%.1f\n", $hash{a}{1}, $hash{b}{1}, $hash{c}{1};

--saintmike


In reply to Re: Interpolating an array element as a hash name. by saintmike
in thread Interpolating an array element as a hash name. by yam

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.