[Gllug] Variadic arguments in perl

Joel Bernstein joel at fysh.org
Tue Oct 24 18:04:48 UTC 2006


On Tue, Oct 24, 2006 at 06:48:18PM +0100, - Tethys wrote:
> I'm sure there's a trivial answer to this, but I'm buggered if I can
> find it. In perl, I want to create a function that take a
> printf()-like format specifier, and a variable number of subsequent
> arguments. I want to sprintf() those arguments into a string, which I
> then do some other stuff with later in the function. The thing I can't
> get to work is passing those arguments into sprintf(). The naive
> approach of:
> 
> $str = sprintf(@_);
> 
> doesn't work. Any ideas?

Perldoc perlfunc 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.

All you need to do is shift off the format arg first:

sub printf_alike {
  my $format = shift;
  my $packed = sprintf($format, @_);
  #...
}

/joel
-------------- next part --------------
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug


More information about the GLLUG mailing list