You had a bug in spr_f() (you end up using a format of "%06" instead of "%06d"). That didn't seem to affect the speed much, though. You also don't return the correct value from concat() so I fixed that too. I made spr_f() a bit faster by eliminating the extra copy. This penalizes concat() since it is now the only one that needs the extra copy (oh well).

I added my favorite (that I learned from chip) and reran the benchmark:

#!/usr/bin/perl -w use strict; use Benchmark qw( cmpthese ); my $num= 13; my $wid= 6; sub concat { my $a= $num; $a= "0$a" while length($a) < $wid; $a; } sub spr_f { sprintf( "%0${wid}d", $num ); } sub sub_s { substr( "0"x$wid.$num, -$wid ); } cmpthese( -3, { CONCAT => \&concat, SPRINTF => \&spr_f, SUBSTR => \&sub_s, }); __END__ Your Results: Benchmark: timing 100000 iterations of CONCAT, SPRINTF... CONCAT: 65359.48/s SPRINTF: 166666.67/s Mine: Rate CONCAT SPRINTF SUBSTR CONCAT 98370/s -- -62% -66% SPRINTF 257009/s 161% -- -10% SUBSTR 286165/s 191% 11% --

Looks like the substr() is fastest.

        - tye (but my friends call me "Tye")

In reply to (tye)Re: Zero Padding by tye
in thread Zero Padding by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.