Testing For A Number

By eric

Although you generally don’t have to worry about types in Perl, it is occasionally necessary to ensure that you are working with numbers. Your test cases should notify you that something is amiss when you didn’t get a number (when you were expecting one). Thankfully Scalar::Util provides a method to deal with this.

1
2
3
4
5
6
7
use Scalar::Util qw( looks_like_number );

my @possibleNumbers = qw(1 5.25 word 4);

foreach my $nums (@possibleNumbers) {
       print "$nums is", looks_like_number($nums) ? '' : ' not', " a number\n";
}

This will print:

1
2
3
4
1 is a number
5.25 is a number
word is not a number
4 is a number

This neat little method takes advantage of Perl C API’s looks_like_number() function. Since this is virtually native, it will be pretty fast.

Follow My Travels

Buy My Book

Archives

  • 2020
  • 2019
  • 2017
  • 2014
  • 2013
  • 2012
  • 2011
  • 2010
  • 2009
  • 2008
  • 2007
  • 2006

New Posts By Email

writing