in reply to Detecting if a scalar has a number or string

Please forgive my newbie ignorance, but I have read the post twice now, and I still don't understand why
if($x =~ m/^[0-9]*$/)
doesn't satisfy your needs.

--
Believe nothing, no matter where you read it, or who said it - even if I have said it - unless it agrees with your own reason and your own common sense.
(Buddha)

Replies are listed 'Best First'.
Re: I don't understand.
by davido (Cardinal) on Nov 19, 2004 at 01:00 UTC

    Well, your regexp won't properly identify:

    1.5 -3 -2.89 .32 0.5 -.01

    ...as numbers. It will also fail to reject empty strings.


    Dave

      Ok, here's a bit of enhancement:
      foreach $abc ("asd","","0","123","-12","1.2","-1.2","12-","-a12","a1") {print "$abc:", is_a_num($abc) ? "Number" : "NaN", "\n";} sub is_a_num { return ($_[0] =~ /^(\+|-)?([0-9]|\.)+$/) || 0 ; }
      Thierry
Re: I don't understand.
by Your Mother (Archbishop) on Nov 19, 2004 at 00:19 UTC

    Among other reasons:

    sub is_a_num { $_[0] =~ m/^[0-9]*$/ } my $not_at_all = ''; print is_a_num( $not_at_all ) ? "Yeppers.\n" : "Nopers.\n";

    Beware the Star of Regex!

Re: I don't understand.
by rrwo (Friar) on Nov 19, 2004 at 13:15 UTC

    Because if $x is an object, then your regex won't work. (Nevermind that it won't work for reals or negative numbers.)

    A stringification method (which your regex assumes) isn't reliable, because I could write a stringification method to output the number in hexidecimal, Base64, or as a roman numeral (see below) but as far as Perl was concerned, it could still operate just like a number):

    package RomanNumber; use Roman 'roman'; sub new { my $class = shift; my $self = { value => shift }; bless $self, $class; } sub as_num { my $self = shift; return $self->{value}; } sub as_string { my $self = shift; return roman($self->as_num); } sub compare { my ($a,$b) = @_; return ($a->as_num <=> $b->as_num); } use overload '0+' => \&as_num, '""' => \&as_string, '<=>' => \&compare;

    If I add a few more numeric operators (it's an incomplete example), Perl can treat it just like a number, except that it outputs a roman numeral in string context.

    There are cases where I would like to require a value to be number, but I would like to give the user of a module the ability to use a 'number-like' object rather than a number.