Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Padding out strings.

by Speedfreak (Sexton)
on Apr 13, 2000 at 18:38 UTC ( [id://7462]=perlquestion: print w/replies, xml ) Need Help??

Speedfreak has asked for the wisdom of the Perl Monks concerning the following question:

Hej all,

This should be simple but I can seem to find a way of doing it in from my Perl book.

I have a string of numbers e.g "123" but I want to pad it out to 5 by adding ones to the front hence making it "00123".

However the string can be variable length, so whats a good way of checking the size of the string, and adding the required number of zeros.

Its not just 5 characters long I need - other areas of my script need 2, 3 and 10. Something generic would be nice.

- Jed

Replies are listed 'Best First'.
Re: Padding out strings.
by btrott (Parson) on Apr 13, 2000 at 19:31 UTC
    Try this:
    sub pad($$) { my $string = shift; my $length = shift; return sprintf "%0${length}d", $string; } print pad 123, 5; print "\n"; print pad 59230, 10;
    Prints:
    00123 0000059230
RE: Padding out strings.
by vroom (His Eminence) on Apr 13, 2000 at 18:45 UTC
    sub pad{ my ($string, $length)=@_; my $padlength=$length-length($string); return "0"x$padlength.$string; } print pad("123",5); print "\n"; print pad("123",6); print "\n";
    This prints out:
    00123
    000123

    vroom | Tim Vroom | vroom@cs.hope.edu
RE: Padding out strings.
by Doc Technical (Initiate) on Apr 14, 2000 at 00:03 UTC
    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;

    }
      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
Re: Padding out strings.
by comatose (Monk) on Apr 13, 2000 at 19:44 UTC

    Here's how you could use sprintf();

    $value = 193; # Want 6 digits, 0 padded?? $value = sprintf ("%06d", $value); # Want 4 digits, 0 padded? $value = sprintf ("%04d", $value);

    You get the idea.

      What do you mean, exactly, by the "first answer"? Both vroom's and my answer's define a pad subroutine that you can give a string and a length that you want the padded string to be. They accomplish the end result in different ways, but both work, and neither assume that you must know the string length beforehand.

        Blech. For some bizarre reason, I was thinking vroom's pad was having the length of the initial string passed to it, not the length of the output string. Whip me and call me an idiot.

RE: Padding out strings.
by Anonymous Monk on Apr 13, 2000 at 19:03 UTC
    just use sprintf. it will generate a string according to your format specification. check perldoc -f sprintf for the info :)
RE: Padding out strings.
by Doc Technical (Initiate) on Apr 14, 2000 at 00:02 UTC
    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; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://7462]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-04-19 10:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found