http://qs321.pair.com?node_id=197562

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

Hi,

Does anyone now a simple and easy way to pad the end of a line with spaces (\s) so its a fixed size.

Example:
I have strings that look like this:
LR20SR37PD30LR23CR23BT01H

I need to have each string a fixed size of 40 chars
Example:
LR20SR37PD30LR23CR23BT01H\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s

Should I use sprintf, and a while loop, or is there an easier way??

Thanks!

Replies are listed 'Best First'.
Re: Padding with \s
by davorg (Chancellor) on Sep 13, 2002 at 13:26 UTC

    Well you can use sprintf, but I don't see why there's any need for a while loop.

    $str = sprintf '%-40s', $str;
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Padding with \s
by busunsl (Vicar) on Sep 13, 2002 at 13:30 UTC
    try:

    my $var = 'LR20SR37PD30LR23CR23BT01H'; $var .= ' ' x 40 - length($var);
    or
    my $var = 'LR20SR37PD30LR23CR23BT01H'; $var = substr($var . ' ' x 40, 0, 40);
    or
    my $var = 'LR20SR37PD30LR23CR23BT01H'; $var = sprintf '%-40s', $var;

      You forgot pack:

      $string = 'abcd' ; $padded = pack('A40',$string) ; print "[$padded]\n" ;

      prints [abcd                                  ]

      ;-)

      Ciao!
      --bronto

      # Another Perl edition of a song:
      # The End, by The Beatles
      END {
        $you->take($love) eq $you->made($love) ;
      }

Re: Padding with \s
by Nemp (Pilgrim) on Sep 13, 2002 at 13:30 UTC
Re: Padding with \s
by jlongino (Parson) on Sep 13, 2002 at 14:05 UTC
    My favorite method uses pack:
    $str = pack('A40',$str);
    Note that this will truncate the string if it is longer than 40 characters.

    --Jim

Re: Padding with \s
by boo_radley (Parson) on Sep 13, 2002 at 13:39 UTC
    you could use concatenation ("the dot operator") :
    my $crypticString="LR20SR37PD30LR23CR23BT01H"; my $acceptableLength=40; my $paddedString =$crypticString . " " x ($acceptableLength - length ($crypticString)); print "'$paddedString'";
    Also, using \s to indicate " " might be confused with the character class \s (which also includes newlines and tabs).
Re: Padding with \s
by abitkin (Monk) on Sep 13, 2002 at 16:27 UTC
    How about this?

    $var .= substr(" " x 40, length($var)) if length($var) < 40;

    The if is so that you don't get warnings about undefined vars.

    If you want to print:
    print $var . (length($var)<40?substr(" " x 40, length($var)):"");

    Though I'm sure someone can optimize it a little better.