WHY are args for sprintf in scalar context?

WHY are args for sprintf in scalar context?

am 31.10.2007 14:25:24 von 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

Re: WHY are args for sprintf in scalar context?

am 31.10.2007 17:11:52 von Mirco Wahab

w.c.humann@arcor.de wrote:
> 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#Contex t_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.