At 6:33 +0900 3/5/01, [EMAIL PROTECTED] wrote:
>?One for the Perl gurus on the list- not a major problem but more of a
>philosophical debate, while doing some date related work I noticed that
>sprintf() & printf() didn't behave as I expected them to, the following
>snippet:
>
>#!perl-w
>
>printf("%2d",((localtime(time))[5])),"¥n";
>
>yields '101' not '01' as I expected (which was: that this would 'round
>down' the number much in the way it 'rounds up' decimals), as I was looking
>to build a short date (ending in '/01' rather than '2001' ) I simply did:
>
Yes. Unix (and therefore Perl) appeared for many years to be returning the
2-digit year in that slot. Not so...they were (and are) returning the year
- 1900.
Just as documented.
This has lead to some odd surprises (such as programs which claim the year
is now 20101 or 19101).
>#!perl-w
>
>printf("%2d",((localtime(time))[5]-100)),"¥n";
>
>and got '1'. Puzzled I went on to test why and found, _gasp_, the padding
>used for non decimal integers by [s]printf() are spaces and not zeros.
You can use either 0 or space as padding...in particular
printf("%02d\n",((localtime(time))[5]-100));
(Note that I've included a newline in the format string and left off the
trailing ', yen n', since the latter confuses me.
>
>Not only that but _none_ of the established sources (PODs, CAMEL,
>COOKBOOK) even touched on this (I think the PODs mumbled something about
>the strings being padded by zeros or spaces depending on circumstance but
>didn't elucidate beyond this) -
>so my question is:
>
>considering how data is normally markedly divided into numbers and strings
>(to the point of giving each dedicated comparison operators) why don't
>printf() and sprintf() pad numbers with zeros and strings with spaces?
It goes back to the early days of C (which produced many mysteries far more
dubious than this one). By now, the answer has unfortunately become
"because."
Also, you can get "stringish" behavior (in Perl, not C) with
printf("%2s\n",((localtime(time))[5]-100));
or, for left-aligned:
printf("%-12snext stuff\n",((localtime(time))[5]-100));
(that's minus 12, not minus 1 followed by 2).
--John
--
John Baxter [EMAIL PROTECTED] Port Ludlow, WA, USA