A subroutine for padding text: defaults pad numbers to left (right justified), alpha right (left justified).
For more edifying and complete solutions, see:
mkmcconn
who sometimes has trouble
telling his right from his left.
#!/usr/local/bin/perl -w
use strict;
my @strings = qw(string justification 999999999 88888888 7777777);
sub justify{
my ($string,
$len,
$char,
$pad_from,
$strict) = @_;
return '' unless defined $string;
$pad_from ||= '';
$pad_from =~ tr{a-z}{A-Z};
$pad_from = '' unless $pad_from =~ s{^([LCR]).*?$}{$1};
if($string =~ m{\D}){
$pad_from ||= 'L';
defined($char ) or $char = ' ';
}else{
$pad_from ||= 'R';
defined($char ) or $char = '0';
}
$len ||= 10;
my $tmpstr = '';
my $offset = 0;
if ($pad_from eq 'R'){
$tmpstr = $char x ($len - length $string).$string;
}elsif($pad_from eq 'C'){
$strict = 1;
my $pad = $char x (int(($len - length $string) / 2));
$tmpstr = $pad.$string.$pad.$char;
}elsif($pad_from eq 'L'){
$tmpstr = $string.($char x ($len - length $string));
}
unless ($strict){
$len = length( $tmpstr )> $len ? length $tmpstr : $len;
}
return (substr($tmpstr,$offset,$len));
}
# EXAMPLES
sub maxsize{
my $maxsize = 0;
my $to_measure = shift;
for (@$to_measure){
my $thissize = length;
$maxsize = $thissize unless $maxsize > $thissize;
}
$maxsize ;
}
my %example = (#pad to default do not truncate
default => q{justify($_)},
#pad to 9, truncate
nine => q{justify($_,9,undef,undef,1)},
#right justify in 9 cols, default pad, truncate
right_ => q{justify($_,9,undef,'R',1)},
#left justify in 9 cols, default pad, truncate
left_ => q{justify($_,9,undef,'L',1)},
#pad ' ' to max len, center
center => q{justify($_,maxsize(\@strings),' ','c')},
#pad '-' to max len default justify
fill => q{justify($_,maxsize(\@strings),'-')}
);
my $padex = maxsize([keys %example]);
for my $ex (sort keys %example){
print justify($ex,$padex,undef,'l',1)." : ".eval($example{$ex})."\
+n" for @strings;
print "\n";
}
__END__
center : string
center : justification
center : 999999999
center : 88888888
center : 7777777
default : string
default : justification
default : 0999999999
default : 0088888888
default : 0007777777
fill : string-------
fill : justification
fill : ----999999999
fill : -----88888888
fill : ------7777777
left_ : string
left_ : justifica
left_ : 999999999
left_ : 888888880
left_ : 777777700
nine : string
nine : justifica
nine : 999999999
nine : 088888888
nine : 007777777
right_ : string
right_ : justifica
right_ : 999999999
right_ : 088888888
right_ : 007777777