Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do printf and sprintf behave differently when only given an array?

Tags:

perl

sub do_printf  { printf @_ }
sub do_sprintf { print sprintf @_ }

do_printf("%s\n", "ok");  # prints ok
do_sprintf("%s\n", "ok"); # prints 2
like image 428
Eugene Yarmash Avatar asked Mar 20 '10 22:03

Eugene Yarmash


3 Answers

sprintf has prototype $@ while printf has prototype of @

like image 192
codeholic Avatar answered Nov 10 '22 03:11

codeholic


From the perldoc on 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.

like image 37
Mark Avatar answered Nov 10 '22 01:11

Mark


See codeholic's and Mark's answers for the explanation as to why they behave differently.

As a workaround, simply do:

sub do_sprintf { print sprintf(shift, @_) }

Then,

sub do_printf  { printf @_ }
sub do_sprintf { print sprintf(shift, @_) }

do_printf("%s\n", "ok");  # prints ok
do_sprintf("%s\n", "ok2"); # prints ok2
like image 35
vladr Avatar answered Nov 10 '22 01:11

vladr