[Canberra-pm] how to tell if a library is available?
Kim Holburn
kim at holburn.net
Tue Jun 17 01:11:56 PDT 2008
My problem is that I want to load and use the module if it's available
but if it's not available I want the script to fall back to other
strategies hopefully without setting off lots of warnings.
I didn't realise that the use statement is a compile time directive.
It obviously works at run time as in the eval but what exactly it does
then I'm not sure. I think from the behaviour I'm seeing that the use
in the eval is not determined at compile time because at compile time
it's just a string. Therefore references to variables in the library
are not linked at compile time unless a naked "use" or "require"
statement appears somewhere.
If the library isn't found then -w generates all sorts of warnings
about strange variables that haven't been declared but I like having -
w on.
I guess what I'd like are some conditional compile directives but they
don't exist. It seems the line in perl between compile directives and
runtime commands is a bit blurry.
On 2008/Jun/17, at 2:15 AM, Paul Fenwick wrote:
> 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
>
--
Kim Holburn
IT Network & Security Consultant
Ph: +39 06 855 4294 M: +39 3494957443
mailto:kim at holburn.net aim://kimholburn
skype://kholburn - PGP Public Key on request
Democracy imposed from without is the severest form of tyranny.
-- Lloyd Biggle, Jr. Analog, Apr 1961
More information about the Canberra-pm
mailing list