Search code examples
perlmoduledetectstrictbareword

Problems with eval and use


I wrote this code and it works when POE module is installed in the system.

#!/usr/bin/perl

use strict;
use warnings;
use POE;

...

But I want to determine if this module exist:

#!/usr/bin/perl

use strict;
use warnings;
eval("use POE; 1") or die ('Please, install POE module. \n');

...

and it returns:

Bareword "KERNEL" not allowed while "strict subs" in use at ./terminalhero.perl line 58.
Bareword "HEAP" not allowed while "strict subs" in use at ./terminalhero.perl line 60.
Execution of ./terminalhero.perl aborted due to compilation errors.

I tried other modules and also had errors. How can I do what I want using strict mode?


Solution

  • The problem is that eval runs after compile time, but your KERNEL and HEAP constants are checked at compile time. So you need to put your eval inside of a BEGIN block:

    BEGIN {
        eval "use POE;";
        die "Unable to load POE: $@\n" if $@;
    }
    

    Although this is mostly an exercise in futility, because a standard use POE; will also die with a useful error if it can't load the module you've requested.