Please note that this question ONLY applies to creating zero-padded numbers, I understand why you would need to use sprintf for other purposes.
Benchmark code below:
use Benchmark; timethese(1000000, { 'Method one' => '&one', 'Method two' => '&two' } +); sub one { my $number = "213"; my $padded = sprintf("%09d",$number); #print $padded,"\n"; # the above line is only uncommented when # benchmarking with 1 loop to test to make # sure resulting number is what we want } sub two { my $number = "213"; my $padded = "000000000"; my $length = length($number); substr($padded,(-$length),$length,$number); #print $padded,"\n"; }
In reply to sprintf vs. substr (for zero-padded values) by Theseus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |