If you don't want to affect your running program at all and speed isn't critical, just fire up a new copy of perl:
#!/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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|