in reply to front-pad a number with zero's

TIMTOWTDI (though sprintf is faster):

sub pad_zeros { my $optimal_length = 5; my $num = shift; $num =~s/^(\d+)$/("0"x($optimal_length-length$1)).$1/e; return $num; }

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: (Ovid) Re: front-pad a number with zero's
by japhy (Canon) on Oct 30, 2001 at 23:32 UTC
    A regex is overkill here. (If I'm saying it, trust me...) If you're against using sprintf(), just do the math:
    sub pad { my ($num, $len) = @_; return '0' x ($len - length $num) . $num; }

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;