On 1 Jun 2001, Chas Owens wrote:
> I want to add functionality to a script using a module, but not do not
> want to require the modules use. It looks like the following code
> works, but is it the best way to achieve my goal (yes, I know TMTOWTDI)?
[...]
> $xls = eval "use Spreadsheet::WriteExcel ; return 1";
A more general solution would be something like,
sub _load_module {
my $module = shift;
my $parms = ref $_[-1] eq "HASH" ? pop @_ : {};
(my $module_file = "$module.pm") =~ s!::!/!g;
eval {
require $module_file;
$module->import;
};
if ($@ =~ /locate $module_file/) {
return 0 if ($parms->{fail_ok});
die qq[\nYou need to install the $module module\n\nTry running\n\n perl -MCPAN -e
'install "$module"'\n\nas root\n\n];
}
die $@ if $@;
return 1;
}
# load LWP::Simple and die with a useful message if it doesn't exist
_load_module("LWP::Simple");
# load Date::Format if we can and set $date_format accordingly (0 if
# we can't, 1 if we can)
my $date_format = _load_module("Date::Format", { fail_ok => 1 });
Exercise for the reader (don't mail the list, but use it in your
programs): Make the function allow parameters for the import call.
(So it can work like 'use Foo qw(function $variable :group);' ...)
:-)
- ask
--
ask bjoern hansen, http://ask.netcetera.dk/ !try; do();
more than 100M impressions per day, http://valueclick.com