http://www.perlmonks.org?node_id=210358


in reply to using 'use' conditionally

If I'm not mistaken, you want to require instead of use in your eval block.   Here's how I did similarly a while back:
my $have_SWE; BEGIN { $have_SWE = 0; eval { require Spreadsheet::WriteExcel }; unless ($@) { Spreadsheet::WriteExcel->import(); $have_SWE = 1; } } if ($have_SWE == 1) { ... }
If memory serves, I picked that up from something merlyn once said or posted.
    cheers,
    Don
    striving toward Perl Adept
    (it's pronounced "why-bick")

Update:
Super Search for "module installed" is what lead me to this thread, where I learnt of BEGIN, eval, and require.

Update:
After discussing with brother BUU, the lone advantage I can see of BEGIN... eval is that it allows you to include a more user-friendly message in the event that Tk isn't installed.   As always, Wiser Monks Than I may very well rightly say that I'm fullabeans.   {grin}

Untested, but perhaps a wee bit cleaner than my original code example:

my $have_Tk; BEGIN { $have_Tk = 0; eval { require Tk }; $have_Tk = 1 unless ($@); } if ($have_Tk == 1) { ... }

Replies are listed 'Best First'.
Re: Re: using 'use' conditionally (require instead of use)
by BUU (Prior) on Nov 05, 2002 at 01:17 UTC
    Why bother evaling? Just do if($opt_g){require Tk;}

      What if the require fails?

        Then you can't run with the -g mode and the user gets a good explanation as to why. I agree with BUU, drop the eval entirely.

                - tye
Re: Re: using 'use' conditionally (require instead of use)
by xafwodahs (Scribe) on Nov 26, 2002 at 22:02 UTC
    When I switch the 'use' to a 'require', I can indeed determine if the module is not installed and catch that.

    However, if the module *is* installed, the Tk code fails to function. There are no errors or anything - the script just exits. I actually placed a 'print' after the MainLoop call, and I see the print output.

    It seems to make no difference whether I call Tk->import;
    It seems to make no difference if I place Tk:: before the tk subroutines.

    bizarre...