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

Tada!

Written by
Open Source software architect and technologist. He's just this guy, you know? Follow him him on Google+.
Published in
Transmissions from the Little Blue Marble

Published October 31st, 2008

Comments

2 Responses

What i needed 🙂 ta

Thank you for this. Much appreciated.

Leave a Reply