in reply to Checking to see if a particular Module is installed

The slowness of string eval (and headache of no compile-time catching of typos inside the eval) is not required here since we have constant code. I'd use:

if( my $got_GD= eval { require GD } ) { GD->import(); }

Note that the import is done at run time (not compile time as would be the case with a use not inside eval), so you can't access your imported routines using barewords (you have to type the parentheses -- and, yes, I'm intentionally ignoring the use of &).

I often like to access imported (or predeclared) routines using barewords because it catches typos at compile time instead of only when that particular typo is executed (writing full coverage test suites is time consuming). But there are no good ways to do that with conditional importing (there are several ways, just none of them are good).

        - tye (but my friends call me "Tye")

Replies are listed 'Best First'.
RE: RE: Checking to see if a particular Module is installed
by merlyn (Sage) on Aug 11, 2000 at 17:03 UTC
    But this still doesn't provide the prototypes of GD subroutines for later parsing, so even though the aliasing is done, we lose the argument context.

    Caveat executor!

    One other problem: your $got_GD is now local to the if, so you won't be able to use it later. So let's rewrite that as:

    my $got_GD = 0; eval { require GD }; unless ($@) { $got_GD = 1; GD->import(); }

    -- Randal L. Schwartz, Perl hacker

      Good call on the problem with placement of my. I don't see your other point.

              - tye (but my friends call me "Tye")
        Your code fails to import prototypes early enough (at compile time) to influence the proper parsing of the later code. For example, say a constant was defined in GD as:
        package GD; sub BIGFONT () { 35 }
        Your code would cause this to be misparsed:
        my $result = BIGFONT + 3;
        because without the empty prototype, BIGFONT is a normal subroutine, and the +3 will be parsed as an argument to the subroutine. With the prototype, we get the proper behavior (and even compile-time constant folding). So, with compile-time importing, we get 38 for the answer, and without, we get 35.

        So, to fix this, wrap my code in a BEGIN block, like so:

        my $have_GD = 0; BEGIN { eval { require GD }; unless ($@) { GD->import(); $have_GD = 1; } }
        Your code does OK without considering prototypes. You haven't been burned, but I'd add the word "yet" there.

        -- Randal L. Schwartz, Perl hacker


        update: Get rid of the "= 0" on the intialization. Sorry.