Testing For A Number

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.

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 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.

Be a loud mouth:
  • Digg
  • Twitter
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • email
  • Ping.fm
  • Reddit
  • Technorati

Related posts:

  1. First Attempt at Poetry: No Substitutes
  2. Mac Perl Problems After Feb Update
  3. Cleaning Up Long Conditionals With Grep
Posted in Perl. Tags: . View Comments

Leave a Reply

blog comments powered by Disqus