in reply to Re^2: How to capture the "isn't numeric" warning?
in thread How to capture the "isn't numeric" warning?
That's exactly what I wanted to know. So, what do you think of my sub?
Sorry, but I don't think it's a good idea. For one, the signal handler will fire on any warning. Scalar::Util's looks_like_number (a core module) calls the internal Perl function that checks if a string looks like a number, so this is just a really convoluted way of calling that function. In your OP, you said "Is there a faster way to test if a variable is a number?", and this is definitely a much slower way to do so - in fact, roughly 38 times slower! As numerous people have said, just use looks_like_number.
use warnings; use strict; use Benchmark qw/cmpthese/; use Scalar::Util qw/looks_like_number/; sub isNumber { @_ or return 0; my $N = shift; defined $N or return 0; my $R = 1; { local $SIG{__WARN__} = sub { $R = 0; }; $N = int($N); } return $R; } cmpthese(-2, { isNumber => sub { isNumber("123") or die; isNumber("-5e7") or die; isNumber("abc") and die; isNumber("") and die; }, looks_like_number => sub { looks_like_number("123") or die; looks_like_number("-5e7") or die; looks_like_number("abc") and die; looks_like_number("") and die; } }); __END__ Rate isNumber looks_like_number isNumber 153840/s -- -97% looks_like_number 5991731/s 3795% --
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: How to capture the "isn't numeric" warning?
by syphilis (Archbishop) on Jun 15, 2019 at 13:33 UTC | |
by ikegami (Patriarch) on Jun 15, 2019 at 15:24 UTC | |
by syphilis (Archbishop) on Jun 17, 2019 at 03:24 UTC |