Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

printf + escape code

0 views
Skip to first unread message

aequ...@yahoo.com

unread,
May 22, 2008, 12:36:49 AM5/22/08
to
Could someone help to explain why the second column is not formatted
with the correct width when escape codes are used?

$ perl -e 'printf ":%-20s:%-20s:\n", "string1", "\e[32mstring2\e[m"'
:string1 :string2 :

Sherman Pendley

unread,
May 22, 2008, 2:42:10 AM5/22/08
to
aequ...@yahoo.com writes:

Perl is counting *all* of the characters in the second variable to find the
amount of padding needed. Not just the "string2" part, but the escape codes
too, because printf() doesn't know about them. The second string is 15 chars
long, counting the escape codes, so printf pads it to 20 chars by adding 5
spaces. It doesn't know that more spaces need to be added to account for the
escape codes being removed.

You could adjust the formatting width for the second string to account for
the escape codes:

$ perl -e 'printf ":%-20s:%-28s:\n", "string1", "\e[32mstring2\e[m"'
:string1 :string2 :

Or, you could put the escape codes in the format string:

$ perl -e 'printf ":%-20s:\e[32m%-20s\e[m:\n", "string1", "string2"'
:string1 :string2 :

Or, include the escape codes separately:

$ perl -e 'printf ":%-20s:%s%-20s%s:\n", "string1", "\e[32m", "string2", "\e[m"'
:string1 :string2 :

I hope this helps!

sherm--

--
My blog: http://shermspace.blogspot.com
Cocoa programming in Perl: http://camelbones.sourceforge.net

0 new messages