Monday, 2007-04-02

Variables in (s)printf formats

Here’s a fun thing I learned for the first time today: you can have variables in formats for printf or sprintf.

Here’s a contrived example:

#!/usr/bin/perl -w
use strict;

sub variable_format {
    my ( $in, $len ) = @_;
    printf( "%0${len}d\n", $in );
}

variable_format( 42, 3 );  # prints 042
variable_format( 42, 9 );  # prints 000000042

Interestingly, I can’t find any mention of this in Perl’s documentation for sprintf.

Tip of the hat to Linus.