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

Hi all
I extract texts between HTML tags to an array and some of
them are pure integer numbers. I need to examin each
item within this array and use those numbers.

if ($item =~ ?????????){
#do something with the number
}

I appreciate any suggestion
Thanks
  • Comment on How to determine a variable value is a number

Replies are listed 'Best First'.
Re: How to determine a variable value is a number
by elusion (Curate) on Aug 03, 2002 at 01:03 UTC
    In a regex, \d stands for a digit, so if you use
    if ($item =~ /^\d+$/) { # do something }
    It will do something for every item that contains only digits. The ^ marks the start and $ marks the end of the string, telling the regex that you want it to match only if every character can be matched. Hope this helps.

    elusion : http://matt.diephouse.com

Re: How to determine a variable value is a number
by larsen (Parson) on Aug 03, 2002 at 13:07 UTC
      Interesting. Let me know if I've got this strait:
      #!/usr/bin/perl -w use strict; sub i_am_a_number { shift; no warnings; # += 0 on a string sets off a warning # make sure that zero is counted as a number # ($_ += 0) alone fails on zero. if (/^\d+$/ || ($_ += 0)) { return 1; } return 0; } ############################################################# # take the sub on a test spin my @list = (035, 35, +19, 12, "045", -2, 5.5, 0, -34.530, "hi!"); for (@list) { if (i_am_a_number($_)) { print "$_ is a number!\n"; } }
      Does this pass muster for zero, signed, and float type numbers?
      ()-()
       \"/
        `                                                     
      
        I don't think that passes muster.... Prove me wrong, but I believe that the expression
        i_am_a_number($_) || i_am_a_number($_)
        will always be true, no matter what value you choose. You might want to rethink what $_ += 0 does for non numbers, especially ones like "12isnotanumber".

        -Blake

Re: How to determine a variable value is a number
by Cine (Friar) on Aug 03, 2002 at 01:04 UTC
    Replace ???? with /^[+-]?\d+$. Remove the [+-]? if you dont have a prefix sign.

    T I M T O W T D I
Re: How to determine a variable value is a number
by Abigail-II (Bishop) on Aug 23, 2002 at 12:56 UTC
    There's also Regexp::Common, which has several regexes for common forms of numbers. Including reals in base 23. (A future version will have regexes for Roman numbers as well).

    Abigail