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

Currently I have this piece of code:
use strict; use warnings; my $input; my $length; print "Enter ID Number: "; $input = <STDIN>; chomp($input); do { $input = "0" . $input; $length = length($input); } until $length eq "11";
The whole point of this is the make $input 11 characters long so it can be compared with another variable read from a file. What I would like to know is is there a better way to do this?

edited: Tue Aug 13 15:05:35 2002 by jeffa - added code tags, removed unnecessary br tags

Replies are listed 'Best First'.
Re: Is There A Better Way?
by Shendal (Hermit) on Aug 13, 2002 at 15:12 UTC
    What you're looking for is sprintf. For example:
    #!/usr/bin/perl -w use strict; print "Enter ID Number: "; chomp(my $input = <STDIN>); die "Not a number!" if ($input =~ /\D/); $input = sprintf("%011d",$input); print "input: $input\n";


    Cheers,
    Shendal
Re: Is There A Better Way?
by simeon2000 (Monk) on Aug 13, 2002 at 15:12 UTC
    sprintf is great for formatting numbers.

    $input = sprintf("%011d", $input);

    That oughtta do the trick.

    --
    perl -e "print qq/just another perl hacker who doesn't grok japh\n/"
    simeon2000|http://holdren.net/

      And since there's more than one way to do it...

      $num = 12; print 0 x (11 - length($num)), $num;

        And some more obfuscated ways listed in this thread - Including my own attempt at obscurity ...

        sub a{$_=int$_[0]*10**$_[1]+.5;s;(.{$_[1]})$;\.$1;;chop if substr($_,- +1)eq'.';return$_};
        ... Although I would not use it in production code myself :-)

         

Re: Is There A Better Way?
by tjh (Curate) on Aug 13, 2002 at 18:44 UTC
Re: Is There A Better Way?
by The_Shadow (Novice) on Aug 13, 2002 at 20:07 UTC
    Thanks all. The sprintf function did it.