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!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.