CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Best way to print hash of hash

 



PerlBeginner31
Novice

Aug 11, 2014, 11:50 PM

Post #1 of 2 (485 views)
Best way to print hash of hash Can't Post

$hash{$a}{$b}++;

What is the best way to print this hash?
I want the output in the following format:

a,b,c

Note: Column a and b must be sorted.

Thanks in advance..


BillKSmith
Veteran

Aug 12, 2014, 6:15 AM

Post #2 of 2 (469 views)
Re: [PerlBeginner31] Best way to print hash of hash [In reply to] Can't Post


Code
use strict; 
use warnings;
my %hash = (
a1 => {
b1 => 5,
b2 => 7,
b3 => 2,
},
a2 => {
b1 => 17,
b2 => 6,
b5 => 9,
},
);

foreach my $aa (sort keys %hash) {
foreach my $bb (sort keys %{$hash{$aa}}) {
print "$aa,$bb,$hash{$aa}{$bb}\n";
}
}


OUTPUT:

Code
a1,b1,5 
a1,b2,7
a1,b3,2
a2,b1,17
a2,b2,6
a2,b5,9


Note: It is a poor idea to use $a or $b as variable names because they conflict with the special variables used by sort. I used $aa and $bb instead.
Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives