I have written a script which will fetch data from db with certain condition and store it in the hash. I need these stored hash content to show in the tabular format.
Right now I have all the data which should be shown in the table is there in the hash called %hash.
I need to display the content of the hash in console in tabular format.
Below is my script:
#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;
my %hash = (
'2022-08-04' => {
'Method 1' => {
'Count' => 50,
'Size' => '10 MB'
},
'Method 2' => {
'Count' => 40,
'Size' => '5 MB'
}
},
'2022-08-05' => {
'Method 1' => {
'Count' => 30,
'Size' => '3 MB'
},
'Method 2' => {
'Size' => '50 MB',
'Count' => '100'
}
}
);
my @cols;
my @keys = ('Method 1', 'Method 2');
foreach my $date (sort keys %hash){
foreach my $method (@keys) {
push (@recs, { date => $date, size => $hash{$date}{$method}{'Size'}, count => $hash{$date}{$method}{'Count'}});
}
}
print "cols:\n".Dumper(\@cols)."\n";
my $line1 = '| ' . join(' | ', map { sprintf "%-*s", 20, $_->{date} } @cols) . ' |';
my $line2 = '| ' . join(' | ', map { sprintf "%-*s", 20, $_->{size} } @cols) . ' |';
my $line3 = '| ' . join(' | ', map { sprintf "%-*s", 20, $_->{count} } @cols) . ' |';
print $line1."\n";
print $line2."\n";
print $line3."\n";
Current Result:
| 2022-08-04 | 2022-08-04 | 2022-08-05 | 2022-08-05 |
| 10 MB | 5 MB | 3 MB | 50 MB |
| 50 | 40 | 30 | 100 |
Expected Result:
-----------------------------------------------------------------------------------
| Date | Method 1 Size | Method 1 Count | Method 2 Size | Method 2 Count |
-----------------------------------------------------------------------------------
| 2022-08-04 | 10 MB | 50 | 5 MB | 40 |
| 2022-08-05 | 3 MB | 30 | 50 MB | 100 |
-----------------------------------------------------------------------------------
Since the data I'm pushing into @cols, each of the cols array element contains a hash with date, size and count. And while printing them it shows in horizontal way instead of showing it in vertically.
Also, sometimes there wouldn't be Method 2 hash values. In that scenario I need to display content of Method 1 hash values in table alone. How to achieve it in dynamic way?
