#!/usr/bin/perl use warnings; use strict; use POSIX qw(_exit); foreach my $mod (qw(CPAN No::Such IO::Socket Not::Installed)) { printf "%20s: %-3s\n",$mod,is_module_installed($mod)?"Yes":"No"; }
sub is_module_installed { my($mod)=@_; return (system("perl -M$mod -e 1 2>/dev/null") == 0); }
sub is_module_installed { my($mod)=@_; defined(my $pid = fork) or die "Fork error: $!\n"; if ($pid) { # Parent waitpid $pid,0; return $? == 0; } else { # Child close(STDERR); eval "use $mod;"; _exit($@?1:0); } }
You could make it a little faster usingfork, to avoid firing up a new interpreter from scratch.
Updated: Tanktalus points out that the copy of perl that system('perl ...') will start may not be the same as the running one; fork will use the currently running interpreter in a new process, so avoids that problem. It should also be a bit faster.
Updated: Fixed Tanktalus' name in previous update. :) Also addressed his concerns about atexit using POSIX::_exit.
In reply to Re: Testing for a module's presence
by sgifford
in thread Testing for a module's presence
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |