in reply to Re: •Re: Re: Help with number conversion
in thread Help with number conversion

A regex?

$number = 42; $number = (' ' x (3 - length $number)) . $number | "000";
Oh wait, let's not do string bit operations ;)
$number = 42; $number = ('0' x (3 - length $number)) . $number;
(The latter is only 50% less efficient than sprintf)

U28geW91IGNhbiBhbGwgcm90MTMgY
W5kIHBhY2soKS4gQnV0IGRvIHlvdS
ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
geW91IHNlZSBpdD8gIC0tIEp1ZXJk

Replies are listed 'Best First'.
(MeowChow) Re5: Help with number conversion
by MeowChow (Vicar) on Apr 03, 2002 at 10:15 UTC
    You can get a substantial improvement over the builtin sprintf with:
    substr "000$num", -3
      
    use strict; use Benchmark qw(cmpthese); my $num = 42; cmpthese (-3, { sprintf => sub { sprintf '%03d', $num }, concat => sub { ('0' x (3 - length $num)).$num }, substr => sub { substr "000$num", -3 }, }); Rate concat sprintf substr concat 244047/s -- -10% -36% sprintf 269956/s 11% -- -29% substr 381628/s 56% 41% --
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print