[Canberra-pm] how to tell if a library is available?
Paul Fenwick
pjf at perltraining.com.au
Mon Jun 16 17:15:01 PDT 2008
G'day Kim / CPM,
Kim Holburn wrote:
> eval "use Text::Autoformat" ;
> if (!$@) {
> use Text::Autoformat ;
> ....
Aha! You've been caught by the fact that "use" statements happen at
compile-time, and not run-time. This means that a "use" inside an if
structure gets executed before perl even looks at the conditional.
The string eval effectively delays loading of the module to run-time, as
well as capturing the error if the module can't be find.
Note that the eval *will* load the module if it's available. If it's not,
it sets $@ with the reason why it could not be loaded (usually because it's
not installed).
This means your code can be written as:
eval "use Text::Autoformat";
if ($@) {
print "Drat, Text::Autoformat not available";
} else {
print "We have Text::Autoformat loaded";
}
All of this assumes that you want to use the module if it's available, which
is usually the case.
> If I don't have the use statement I get lots of other errors (using -w).
I can only guess these are genuine warnings that relate to the rest of the
code, but not the specific task of loading a module.
Cheerio,
Paul
--
Paul Fenwick <pjf at perltraining.com.au> | http://perltraining.com.au/
Director of Training | Ph: +61 3 9354 6001
Perl Training Australia | Fax: +61 3 9354 2681
More information about the Canberra-pm
mailing list