I have a trivial project that has turned into something beyond my scope with recursive algorithms in perl. The following script does almost everything that I need, except print the full path to each value.
eaxmple:
3 => 6
should be
II/B/3 => 6
Please note that the final hash is unknown at runtime, and can be of any size and depth. The output format is specific to an old program that we still use, else I would just dump it using Data Dumper.
#!/usr/bin/perl -w
use strict;
my %hash = (
'I' => 1,
'II' => {
'A' => 3,
'B' => {
'1' => 4,
'2' => 5,
'3' => 6}
},
'III' => 2
);
print_hash(\%hash);
sub print_hash {
my($href) = @_;
foreach my $key (keys %$href) {
if (ref($$href{$key}) eq 'HASH') {
my $href2 = $$href{$key};
print_hash($href2);
}
else {
print "$key => $$href{$key}\n";
}
}
}
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.