~~David~~ has asked for the wisdom of the Perl Monks concerning the following question:

All, I was wondering if there was a more nice way of accomplishing the following than what I have already written.
I have a number that can be anywhere from 0 - 999999. I am using this number to look up a corresponding file, and the file always has the number in all six digits, so if I pull the number 54 from a log file, I need to pull file 000054.zip. I am currently doing the following, and it seems cumbersome and long:
my $longdefectid; if ($defectid < 10){$longdefectid = "00000"."$defectid"} elsif($defectid >= 10 && $defectid < 100){$longdefectid = "0000"." +$defectid"} elsif($defectid >= 100 && $defectid < 1000){$longdefectid = "000". +"$defectid"} elsif($defectid >= 1000 && $defectid < 10000){$longdefectid = "00" +."$defectid"} elsif($defectid >= 10000 && $defectid < 100000){$longdefectid = "0 +"."$defectid"} elsif($defectid >= 100000 && $defectid < 1000000){$longdefectid = +"$defectid"};
Is there anything shorter or nicer than this?
~~David~~

Replies are listed 'Best First'.
Re: Formating Numbers Preceding 0's
by Somni (Friar) on Nov 27, 2007 at 23:52 UTC
Re: Formating Numbers Preceding 0's
by chrism01 (Friar) on Nov 28, 2007 at 00:34 UTC
    Just for fun:

    '0' x (6-length($defectid)).$defectid

    Cheers
    Chris

Re: Formating Numbers Preceding 0's
by dwm042 (Priest) on Nov 28, 2007 at 01:40 UTC
    This is one way to accomplish the task:

    #!/usr/bin/perl -w # # my @data = (7, 314, 23, 513465, 4444, 29 ); for (@data) { print " Num: ", six_zeroes($_), "\n"; } sub six_zeroes { my $num = shift; return substr("000000" . $num, -6 ); }
    And the results are:

    ~/perl/perlmonks$ ./leading_zeroes.pl Num: 000007 Num: 000314 Num: 000023 Num: 513465 Num: 004444 Num: 000029