WHY are args for sprintf in scalar context?

W

w.c.humann

Just ran into this nasty trap:
perl -we'@a=("%s %s\n", qw/foo bar/); printf @a' foo bar
perl -we'@a=("%s %s\n", qw/foo bar/); print sprintf @a'
3

And indeed, 'perldoc -f sprintf' says:
"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."

But *why* are args for printf in array context and for sprintf in
scalar context? Especially if it's "not what I probably mean" and
"almost never useful". It's not like Perl to make easy things
harder...

Wolfram
 
M

Mirco Wahab

But *why* are args for printf in array context and for sprintf in
scalar context? Especially if it's "not what I probably mean" and
"almost never useful". It's not like Perl to make easy things
harder...

This seems to be old news ;-)

http://www.perl.com/pub/a/1999/11/sins.html#2
http://www.perl.com/doc/manual/html/pod/perltrap.html#Context_Traps_scalar_list_con

IIRC, this distinction (printf/sprintf) came in
after porting from Perl4 to Perl5 because printf
accepts an optional filehandle as first argument
and sprintf allows format construction by subroutine
return value there. One of Perls oddities, true.

...
@a = ("%s %s\n", qw/foo bar/);
print sprintf shift @a, @a;
...

Regards

M.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top