The simplest way is to copy and paste the sub into your program, although a better approach would be wrapping this in a class or module etc. And you just need to call the sub as showed below (observe the result from the print out, you will see some missing lines when the input is not numeric.):
sub AsNumber { my ($s) = @_; return undef unless defined( $s ); my $number; eval { # make conversion failure a fatal error use warnings FATAL => qw(numeric); # try to use $s as a number $number = 0 + $s; }; if ($@) { # exception happened, thus not a number $number = undef; } return $number; } print AsNumber(123), "\n"; print AsNumber("123"), "\n"; print AsNumber("abc"), "\n"; print AsNumber(1.2e-10), "\n"; print AsNumber(1.23), "\n"; print AsNumber("1.2a"), "\n";
In reply to Re: How to implement numeric checking in my program.
by PeterPeiGuo
in thread How to implement numeric checking in my program.
by Tails
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |