All,
Earlier today, I was faced with a problem that amounted to:
for my $let (keys %hash) {
for my $num (keys %{$hash{$let}}) {
for my $name (keys %{$hash{$let}{$num}}) {
print join(',', $let, $num, $name, $hash{$let}{$num}{$name
+}), "\n";
}
}
}
The trouble was, the data structure was going to be an arbitrary number of levels deep. My first inclination was to reach for Algorithm::Loops but it didn't seem like a good fit. My second idea was to write an iterator (see Arbitrarily Nested Loops) but I wanted a coworker who is just learning perl (former C++ developer) to be able to maintain it. In a few minutes, I came up with a recursive solution which surprised me.
On my way home, I thought of several other ways of doing it and I was wondering how others might solve the problem. That is my question - how would you do it? I have provided my recursive solution below to get the ball rolling.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.