Forum Moderators: coopster & phranque

Message Too Old, No Replies

sprintf()

         

DrDoc

6:37 pm on Jul 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



sprintf("%15s","foo") returns a 15 character string, with 12 leading spaces, and "foo" at the end...
How can I get it to pad with anything but spaces?

Glacai

8:22 pm on Jul 15, 2004 (gmt 0)

10+ Year Member



Not sure this is what you wanted but to pad it with z's,
sprintf("%'z15s", "foo");

Added: Sorry done it again, didn't realise this was for perl, off to check if it works the same...

DrDoc

1:48 am on Jul 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes, that's exactly what I want to do... But, no... It doesn't work in Perl :(

SeanW

1:13 pm on Jul 16, 2004 (gmt 0)

10+ Year Member



You could always do a substitution:

$foo = sprintf(....);
$foo =~ s/^ +/z/;

Formats might help you depending on what you're trying to accomplish:

[perldoc.com...]

Sean

DrDoc

5:41 am on Jul 18, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I thought about that, but I don't want to replace spaces already existing before using sprintf(). Consider the following:

$foo = "hi ho";
print sprintf("%15s",$foo);

Now, I'd really like that to be **********hi ho, but using a regexp to replace the spaces would result in **********hi*ho, which is not what I want :)
I guess I'll just have to count the string length, and pad manually. :)

SeanW

6:03 pm on Jul 18, 2004 (gmt 0)

10+ Year Member



DrDoc, I think you should look at the regexp I gave you closer. The spaces are only matched and replaced if they occur at the beginning of the string -- it does what you want.

Sean

DrDoc

5:36 pm on Jul 19, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sorry, I wasn't clear enough. You are right, it only replaces leading spaces. But, if the string begins with a space I want that space preserved.