Random Perl: How to check if something is a number

Friday, October 31st, 2008 at 11:51 pm

Perl has no built in function or sub to test if a variable is a number or not. Scalar::Util makes it easy, and is a core module as well.

use Scalar::Util qw(looks_like_number);

my $number = 192;
my $string = '123foobarbazquux123';

if(looks_like_number($number)) {
  print "$number is a number!\n";
}

if(!looks_like_number($string)) {
  print "$string is not a number!\n";
}

Tada!

2 Responses to “Random Perl: How to check if something is a number”

Leave a Reply