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

Hi , Can Any one help me in attaining a solution in validating a data , I need to validate only a integer or decimal and invalidate a string of alpha numeric Example my @numbers = (0, 3.14, 5 "any strings can come here 234 "); In my case the first three are valid so i need to invalidate the last string value I need a solution other than using Data::Types . Thanks & Regards

Replies are listed 'Best First'.
Re: Valid Numbers or decimals
by Nevtlathiel (Friar) on May 06, 2005 at 10:49 UTC
    Just use a regular expression to check that your variable only contains a decimal place (\. - you need to escape it in the regular expression) and \d (digits 0-9). :)
    ----------
    My cow-orkers were talking in punctuation the other day. What disturbed me most was that I understood it.
Re: Valid Numbers or decimals
by davidrw (Prior) on May 06, 2005 at 13:25 UTC
Re: Valid Numbers or decimals
by zentara (Cardinal) on May 06, 2005 at 11:34 UTC
    I'm not a regex guru, but how about:
    #!/usr/bin/perl my @numbers = (0, 3.14, 5 , "any strings can come here 234 "); print "@numbers\n"; my @numgoods = grep{/^(\d*\.?\d+)$/ } @numbers; print "@numgoods\n";

    I'm not really a human, but I play one on earth. flash japh
      If the OP want to treat a number that ends with a decimal point (e.g., 7.) as valid, the above regular expression needs to be tweaked. Something like  grep { /^\d*\.?\d+$/ || /^\d+\.?$/ } should work.
        neither of these cope with the fact that...
        my $num = 1_000_000;
        ...is a perfectly valid number declararion. I think what the OP is after is way to get at what Perl is doing when it compains after you do something like this...
        my $num = 1_000_000; if ($num == "ssf") { print "uh oh"; }
        Re-writing an existing Perl check in a regex is best avoided if possible IMHO
        ---
        my name's not Keith, and I'm not reasonable.