perlit perlit - 1 year ago 62
Perl Question

Is it possible to pass sprintf type arguments to a Perl function?

Consider the following sample code.

my $a = "test";
my $b = "stackoverflow";

test("%s - %s\n", $a, $b);

sub test {
my $error = sprintf(@_);
print $error;

This prints 3 and not a formatted string. Is it even possible to do what I'm trying?

cjm cjm
Answer Source

As VGE suggested, it's the prototype that's causing problems, but you need to use shift, not pop:

sub test {
    my $error = sprintf(shift, @_);
    print $error;

sprintf evaluates its first argument in scalar context. If that's an array, you get the length of the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download