perlit perlit - 3 months ago 8
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

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.