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

Hi, I want to write a zipcode to a flat file but find that zip codes such as 09876 lose the leading 0 and display as 9876. How can I force this to be length 5 with a leading 0? Thanks...

Replies are listed 'Best First'.
Re: formatting zipcodes
by Kanji (Parson) on Apr 14, 2002 at 22:14 UTC

    See (s)printf, which can be coerced into right-padding with zeros (instead of spaces) if the string is shorter than a desired length...

    my $zip = sprintf "%05d", 9876;

        --k.


      perfect, thanks(all) for the quick reply
        If you are writing this code for international use remember that not all postal codes are five digits. The post codes in Australia, for example, are 4 digits long.
(MeowChow) Re: formatting zipcodes
by MeowChow (Vicar) on Apr 15, 2002 at 04:33 UTC
    $zip = substr "0000$zip", -5;
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
Re: formatting zipcodes
by tmiklas (Hermit) on Apr 15, 2002 at 11:43 UTC
    If i understand you well, then you have at least 2 (simple) solutions:
    1. Brute force:
      print "0" x (5 -length($zip)), "$zip";
    2. Much more elegant ;-):
      printf ("%05d", $zip);

    I would use the second one ;-)

    Greetz, Tom.
Re: formatting zipcodes
by thelenm (Vicar) on Apr 16, 2002 at 15:24 UTC
    Another thing you should consider is representing the zip code as a string, not a numeric value. Unless you're doing some sort of math on zip codes, there's really no reason it has to be numeric. Also, as someone pointed out, international postal codes come in various formats. With postal codes stored as strings, your program could be more easily modified later on if it needs to handle those as well.
    my $zip = "09876"; print "Zip is: '$zip'\n";
Re: formatting zipcodes
by BUU (Prior) on Apr 14, 2002 at 22:13 UTC
    either assume leading 0 if length = 4, or use dbl quotes around it