ttlgreen has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I'm trying to figure out how to test if the Term::ANSIColor module is present, and if so "use" it.

I'm trying to get the equivalant functionality as doing:

use Term::ANSIColor qw(:constants);

The problem is I need to use require instead so the script doesn't exit when it's not found, and I can't seem to get the :constants that way...

The code:

my $can_color = 0; eval { require Term::ANSIColor; }; unless ($@) { ## I tried these next two lines but it does NOT seem to work (compla +ins about the constants not being defined)... Term::ANSIColor->import(); Term::ANSIColor->import(qw(:constants)); $Term::ANSIColor::AUTORESET = 1; $can_color = 1 }

What could I be missing?

Thanks!

Replies are listed 'Best First'.
Re: can't seem to import properly when using require
by Anonymous Monk on Feb 26, 2012 at 22:29 UTC

    What could I be missing?

    A BEGIN{} block

    As in

    BEGIN { eval { require Term::ANSIColor ; 1; } and do { Term::ANSIColor ->import( ); Term::ANSIColor ->import( qw/:constants / ); }; }

    See also Re: Best way to dynamically use a .pm?

      Perfect! Thanks!

        I see you have yet to test in an environment where Term::ANSIColor isn't installed.

        You also didn't actually show any of the code where the errors actually happen.

        You can't conditionally use compile-time magic unless you also only conditionally compile the magic-using code.

        So, I usually drop the BEGIN block and fix my code so it does not depend on compile-time magic from the optional module. But, looking at the docs for Term::ANSIColor, it looks like it flings compile-time magic all over the place. So you might find it easier to conditionally compile any code that makes use of said magic.

        Not that I will help with that since you didn't include any of said magic-using code (that was failing).

        - tye