sprintf oddness

gav on 2004-09-17T20:03:20

I've found this odd thing with sprintf, probably to do with it's prototype.

I would have thought that sprintf @list would do the same as sprint shift @list, @list, but it's doesn't. The former will return the number of elements in @list.


It's in the docs

davorg on 2004-09-17T20:15:23

From "perldoc -f sprintf":

Unlike "printf", "sprintf" does not do what you probably mean when you pass it an array as your first argument. The array is given scalar context, and instead of using the 0th element of the array as the format, Perl will use the count of elements in the array as the format, which is almost never useful.

Re:It's in the docs

Mr. Muskrat on 2004-09-17T20:43:08

"Perl will use the count of elements in the array as the format, which is almost never useful."

When would that be useful? I can't think of a single case.

Re:It's in the docs

vsergu on 2004-09-17T21:31:48

To solve some bizarre problem on Fun With Perl?

Re:It's in the docs

gav on 2004-09-17T23:26:53

Doh! I feel like a moron for looking up the docs for sprintf and not noticing that.

It's a good example of getting bitten by an unexpected prototype though...

Hysterical Raisins

schwern on 2004-09-18T01:40:45

I suspect printf and sprintf behave differently because of print/printf's non-standard prototype. sprintf is $@, as it should be. printf should also be $@ except for the filehandle oddity that can't be expressed in prototypes. It could probably be fixed these days but then the Backwards Compatibility Police will come in the night and rearrange your furniture.

Another "print sprintf" vs "printf" surprise I noticed a while ago: printf doesn't honor $\.