Hi Monks! I've got a bit of a question which i'm hoping could make one of my scripts a bit more concise

Essentially i have a hash of arrays (massively simplified):

my %hash=('ID' => { 'key1' => [key1_val1, key1_val2], 'key2' => [key2_val1, key2_val2] } );

And i need to expand it out to look like this:

ID, 1, key1_val1, key2_val1 ID, 2, key1_val1, key2_val2 ID, 3, key1_val2, key2_val1 ID, 4, key1_val2, key2_val2

So each key is a field of data With various values and i need to expand out a single line for each combination given. As i said, this i massively simplified and i actually have ~15 'keys' and each can have about 11-12 values in it's array.

I'm currently doing it the obvious way of:

my $id2=1; my %data=(); foreach my $id (keys(%hash)) { foreach my $key1_val (@{$hash{$id}{'key1'}}) { foreach my $key2_val (@{$hash{$id}{'key2'}}) { $id2++; $data{$id}{$id2}{'key1'}=$key1_val; $data{$id}{$id2}{'key2'}=$key2_val; } } }

Which is fine but everytime i add a new field it get a bit unwieldy. I have "foreach" statements running off the side of the monitor and onto my wall!! Help!

Apologies if there's any mistakes in the above. It's been a long day. Any help appreciated as ever!


In reply to Massive expansion of a hash of arrays? by Amblikai

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.