Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Padding with \s

by Anonymous Monk
on Sep 13, 2002 at 13:21 UTC ( #197562=perlquestion: print w/replies, xml ) Need Help??

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


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

I have strings that look like this:

I need to have each string a fixed size of 40 chars

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


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;

    "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

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

      You forgot pack:

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

      prints [abcd                                  ]



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

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.


Re: Padding with \s
by Nemp (Pilgrim) on Sep 13, 2002 at 13:30 UTC
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.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2021-11-28 03:39 GMT
Find Nodes?
    Voting Booth?

    No recent polls found