Archive for October, 2008

Random Perl: How to check if something is a number

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";