Archive for the 'Perl' Tag

Random Perl: How to check if something is a number

Friday, October 31st, 2008

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!

Random Perl: Application local modules

Tuesday, October 14th, 2008

Perl apps sometimes need modules that belong to them and aren’t installed into any global path.

Consider the following code:

use File::Spec::Functions qw(catpath splitpath rel2abs catdir);
use lib catpath((splitpath(rel2abs $0))[0, 1], catdir(qw(lib)));

If my program was named application (full path is /home/diablo/application-1.2.3/application), no matter how I ran it (via full path, ./application, ../application-1.2.3/application, /symlink_to_application-1.2.3/application, etc) or what I ran it from (console, fastcgi, mod_perl, etc), this code can find the directory named lib (full path is /home/diablo/application-1.2.3/lib/), and add it to Perl’s internal list of directories to look for modules in (aka @INC).

Thanks Aristotle!