in reply to Padding out strings.

My preferred method:

#!/usr/bin/perl

# padding a string with leading zeros
# - $num is the number to be padded
# - $pad is the total number of digits you want in the result

$num = "345";
$pad = 5;
$paddednum = &pad_num($num, $pad);
print "num is $num, padded num is $paddednum\n";

exit(0);

##############################

sub pad_num {

# how it works:
#
# "0"x$pad yields ($pad) zeros, i.e. "0" x 5 yields "00000" ...
# this is prepended to $num, yielding a string with ($pad) zeros
# and the number. This becomes the first arg to the substr fn
#
# ($pad * -1) is the second arg to substr ... when 2nd arg to
# substr is negative, substr counts backward from the end of the string
#
# $pad is the third arg to substr
#
# thus if $pad is 5 and $num is 345,
# result is substr( "00000345", -5, 5 ) or "00345"

my ($num, $pad) = @_;
my($paddednum) = substr( (("0"x$pad).$num), ($pad*-1), $pad );
return $paddednum;

}

Replies are listed 'Best First'.
Re: RE: Padding out strings.
by softworkz (Monk) on Jul 30, 2001 at 18:40 UTC
    I've had to do something like this awhile back so here's my baby perl version. Have fun!
    #!/usr/bin/perl-w use win32; use strict; # uncomment this out if you want to input the amount of chars #if($#ARGV < 0) { # die "usage: program.pl <padding chars> \n" # . "for example: program.pl 30\n" #} #my $padlength = $ARGV[0]; my $in_name=$ARGV[0]; open(FILE,"numbers.txt") || die "numbers.pl can't open file: $!"; open(OUTPUT,">numberdump.txt") or die "numbers.pl can't open file: $!" +; while (<FILE>) { chomp; # sample input: # UserID Date # 423Hm54 ATHENA02 10/1/2000 # 123456Dh60 ATHENA02 10/1/2000 # 18Dh60 ATHENA02 10/2/2000 # 10Jch6 ATHENA05 10/2/2000 # 54321Hh24 ATHENA05 10/2/2000 # 21Mwm22 ATHENA03 10/2/2000 #Look only at the summary lines where $_ == 2000 next unless ($_ =~ /2000/i); # this is to clean up the first variable length field my $padchar = "0"; my $count = length($_); my $padlength = 30; # comment this out if using ARGV $padchar = $padchar x ($padlength-$count); print $padchar, $_, "\n"; print OUTPUT $padchar, $_,"\n"; } close FILE; close OUTPUT; # sample output: # 000423Hm54 ATHENA02 10/1/2000 # 123456Dh60 ATHENA02 10/1/2000 # 000018Dh60 ATHENA02 10/2/2000 # 000010Jch6 ATHENA05 10/2/2000 # 054321Hh24 ATHENA05 10/2/2000 # 00021Mwm22 ATHENA03 10/2/2000