use warnings; use strict;
use List::Util qw[ max ];
my %p =
( 'a' => 1
, 'm l n o p q' => 20
, 'x y z' => 321
);
my $max = max map { length $_ } keys %p;
my $format = "%-${max}s %d\n\n";
my $out = '';
for ( sort keys %p )
{
$out .= sprintf $format , $_ , $p{ $_ }
}
print $out;
Main thing is to find out the maximum length of each column that may affect the format (alignment if you like), to be used in sprintf format specification. In case numbers should be aligned with right margin ...
use warnings; use strict;
use List::Util qw[ max ];
my %p =
( 'a' => 1
, 'm l n o p q' => 20
, 'x y z' => 321
);
my $name = max map { length $_ } keys %p;
my $number = max map { length $_ } values %p;
my $format = "%-${name}s %${number}d\n\n";
my $out = '';
for ( sort keys %p )
{
$out .= sprintf $format , $_ , $p{ $_ }
}
print $out;
|