Formatting with a leading + / Lua and Perl
Archive - Originally posted on "The Horse's Mouth" - 2008-10-15 11:57:46 - Graham EllisIn formatted printing, you can often use a leading "+" in the format string to force a positive sign to be added in front of positive numbers - for example "%+4d" means an integer, to base 10, 4 character positions as a minimum, right justified.
Here's an example of that, in code, in Lua
for john = -10, 10, 1 do
print (string.format("xx %+4d yy",john))
end
And here is how it runs:
[trainee@easterton o8]$ lua sf
xx -10 yy
xx -9 yy
xx -8 yy
xx -7 yy
xx -6 yy
xx -5 yy
xx -4 yy
xx -3 yy
xx -2 yy
xx -1 yy
xx +0 yy
xx +1 yy
xx +2 yy
xx +3 yy
xx +4 yy
xx +5 yy
xx +6 yy
xx +7 yy
xx +8 yy
xx +9 yy
xx +10 yy
[trainee@easterton o8]$
The same technique applies in Perl, and in other languages too.
Other leading characters:
0 - Leading zero fill
- - Left justify