data structures - Efficient way of printing hash of hash of arrays in Perl -
i writing script involves printing contents of hash of hash of arrays.
ex (pseudo code):
my %hash = (); $hash{key1}{key2} = ['value1', 'value2', 'value3', . . .];
or
$hash{key1}{key2} = @array_of_values;
basically want able number of key combinations , able loop through of possible key/value pairs (or more correctly stated key,key/array pairs since each value array of values , each array has 2 keys associated it) , print output in following format:
"key1, key2, value1, value2, value3, . . .\n"
ex:
#!/usr/bin/perl use strict; use warnings; # initialize hash %hash = (); $string1 = "string1"; $string2 = "string2"; # push strings onto arrays stored in hash push @{$hash{a}{b}}, $string1; push @{$hash{a}{b}}, $string2; push @{$hash{c}{d}}, $string2; push @{$hash{c}{d}}, $string1; # print elements of hash # (want loop possible key/value pairs) local $, = ','; print "a, b, "; print @{$hash{a}{b}}; print "\n"; print "c, d, "; print @{$hash{c}{d}}; print "\n"; system ('pause');
the output code shown below:
a, b, string1,string2 c, d, string2,string1 press key continue . . .
i thinking using each
operator appears work 1 dimensional hashes. (each
returns 1 key value pair, not work correctly when there 2 keys involved)
how can streamline code traverse through hash in loop , print desired output regardless of how big hash gets?
sounds need nested loop ... there's way map
harder remember , less readable ;-) (speaking myself of course - forward seeing map
solution appear here!):
#!perl -l %hash = (); $hash{key1}{key2} = ['value1', 'value2', 'value3',]; $outer (keys %hash) { $inner (keys $hash{$outer}) { print join(', ', $outer, $inner, @{ $hash{$outer}{$inner} } ) } }
output:
key1, key2, value1, value2, value3
there's data::printer
, data::seek
,data::dive
, several other convenience modules if things complicated. require use of hash references though may complicate simpler solution or make larger , more difficult problem more possible ...
cheers,
edit: moved "nested map" separate answer.
Comments
Post a Comment