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

Hi, Using regex, I have taken a value and now I want to report a error message if it is not a numeric value. My lines are below:

if($_ =~ /<blk id="(.+?)"\/>/g) { my $blk=$1; if($blk != \d){print "Invalid value"} }

Now, whether the value is 1 or abc, I am not getting the error. It should accept 1 but not abc. Could anyone help me to identify what's wrong in the code?

Replies are listed 'Best First'.
Re: Checking whether a value is numeric or not
by almut (Canon) on Nov 27, 2008 at 08:20 UTC

    Regexp::Common might keep you from reinventing the wheel:

    use Regexp::Common; while (<DATA>) { chomp; /^$RE{num}{real}$/ and print "$_ is a number\n"; } __DATA__ 123 abc 0.123
Re: Checking whether a value is numeric or not
by Krambambuli (Curate) on Nov 27, 2008 at 08:08 UTC
    Well, what exactly do you define as being a "numeric value" ?

    7.89e-200 ? 0xabc ? They both are numeric values...

    If you think about a string of exclusive decimal digits, you might want to rewrite your test as
    if($blk !~ /^[\d]+$/) {print "Invalid value"};
    or so.

    Krambambuli
    ---

      For this particular case, I would probably use:

      if($blk =~ /\D/) { print "Invalid value";}

      For some reason, it seems clearer to me.

      G. Wade
Re: Checking whether a value is numeric or not
by hda (Chaplain) on Nov 27, 2008 at 10:18 UTC
    Hi,

    Why not try Scalar::Util ?

    use Scalar::Util qw(looks_like_number); if (looks_like_number($your_number)) { do something; }
Re: Checking whether a value is numeric or not
by Gangabass (Vicar) on Nov 27, 2008 at 08:25 UTC
    perldoc -q number

    Use Super Search to quickly find answers to your questions