in reply to How to identify a number datatype in a string?

USe an eval, it's correct (by definition) and avoids possible errors

my @numbers = ( '1', '2', '10', '1.2', '1e2', '1.02e2', '1.02e-2', 'e-2', 'er', 'et', '0er' ); foreach my $number (@numbers) { my $test = $number; eval { $test +=0; }; if ( $@ ) { print "$number isn't a number \n"; } }

{QA Editors note: This solution doesn't work as described. See Re: Answer: How to identify a number datatype in a string? for more explanation.}

Edited by davido: Repaired <code> tags, reformatted code. Added editorial note to clarify why this example is broken.

--

Anthony Staines

Replies are listed 'Best First'.
Re: Answer: How to identify a number datatype in a string?
by hossman (Prior) on May 30, 2003 at 06:31 UTC
    Uh, this doesn't seem to work at all...
    laptop:~> perl -T my @numbers = ('1','2','10','1.2','1e2','1.02e2', '1.02e-2','e-2','er','et','0er', 'total and complete non number stuff'); foreach my $number (@numbers) { my $test = $number; eval { $test +=0; }; if ( $@ ) { print "$number isn't a number \n"; } } laptop:~>
    Here are my particulars...

      Add the following after if(@){}, and you will see...

      else { print "number: ", $test , "\n"; }

      ...Apparently, $test is assigned zero (perl 5.8.0) when $number is not a number. Ergo, no errors in eval, no print.

        Acctually, $test is assigned $number regardless of what $number is ... if you do any mathematicly operations on a scalar which is "not a number" then that scalar is evaluated as "0" (and a warning is generated).

        Which was basicly my point ... the whole premese of this test is flawed. (uless you set up a signal handler for warnings, which causes a "die" to be thrown)