Perl printf() and strings
I understand how printf works with numbers but i am a bit confused when it is used with strings.
in:
%-w.dx
I uderstand that % is the field specifier marker, and a minus sign means to align to the left, and that w is the TOTAL width of field.
My problem arises when ther is a decimal point (as in above) and a value for d (which i have seen written as "The total allowable width of the field FOR STRINGS). I dont understand the difference between w and d (above).
Example.
printf ("%-15.5s", $stringValue);
Here, the feild is 15 characters long, but what does the .5 mean.
Thanx in advance:confused:
Abhishek Reddy posted this at 04:50 — 26th November 2006.
He has: 3,348 posts
Joined: Jul 2001
The dash and dot flags are independent of each other, so forget about -15 for a moment. [incode]printf("%.5s", $stringValue);[/incode] is what you're asking about.
The dot flag is used to specify precision or maximum width of a value. In this case, as the argument is a string, the .5s would truncate it to 5 characters if its length was in excess of 5:
> printf ("%.5s", "foo");
> foo
> printf ("%.5s", "foobarbaz");
> fooba
Precision or maximum width mean different things for other types of arguments, such as integers, floats, etc. Refer to the sprintf perldoc for more.
StuPeas posted this at 11:32 — 26th November 2006.
They have: 36 posts
Joined: Oct 2004
Cheers Abhishek
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.