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

Hello fellow monks,

I have a very simple problem, I need to somehow pad a number to be 4 characters in length so I always end up with a 4 byte word.

For Example:
2 needs to be 0002
15 needs to be 0015
...
I have to have the leading zeroes.

Any suggestions?

Replies are listed 'Best First'.
Re: Reg Exp Suggestion Needed
by theorbtwo (Prior) on Sep 05, 2002 at 01:03 UTC

    You don't need a regex for this; use sprintf instead. Specificly...

    @numbers = (2, 15, 1, 12, 123, 1234, 12345); @numbers = map {sprintf '%4.4d', $_} @numbers; print join ',', @numbers; __END__ 0002,0015,0001,0012,0123,1234,12345


    Confession: It does an Immortal Body good.

Re: Reg Exp Suggestion Needed
by dws (Chancellor) on Sep 05, 2002 at 01:04 UTC
    I need to somehow pad a number to be 4 characters in length so I always end up with a 4 byte word.

    There's an option in sprintf that'll help you get what you need.

    perldoc -f sprintf

Re: Reg Exp Suggestion Needed
by dpuu (Chaplain) on Sep 05, 2002 at 01:04 UTC
    $padded = sprintf("%04d", $value);
    --Dave
Re: Reg Exp Suggestion Needed
by kelan (Deacon) on Sep 05, 2002 at 01:05 UTC
    I don't think there's a way to make sure the variable is always 4 bytes other than to format it before you use it.
    $var = sprintf('%04d', $num);
    Works well to zero-pad the number for printing, but if you do any arithmetic on it, you'll need to repad it, because perl will take off the leading zeroes.

    kelan


    Yak it up with Fullscreen ChatBox

Re: Reg Exp Suggestion Needed
by Zaxo (Archbishop) on Sep 05, 2002 at 01:04 UTC

    perl -e'printf "%04d \n%04d\n", 2, 15

    Also see sprintf.

    After Compline,
    Zaxo

Re: Reg Exp Suggestion Needed
by Anonymous Monk on Sep 05, 2002 at 01:20 UTC
    Thank you for the help!
Re: Reg Exp Suggestion Needed
by AcidHawk (Vicar) on Sep 05, 2002 at 09:41 UTC
    Hi, I used this once before. It might just be another way of doind it...
    $call = "0000000000000"; $call_num = $ARGV[0]; substr($call, -length($call_num)) = "$ARGV[0]"; print "$call\n";

    -----
    Of all the things I've lost in my life, its my mind I miss the most.