2

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?

ciembor
  • 7,189
  • 13
  • 59
  • 100

1 Answers1

8

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • This way, if the program were feeling devilishly proactive, it could automatically download and ask to install the missing module. But that might cause more harm than good, really. – Jon Purdy Nov 29 '11 at 01:04
  • @JonPurdy: Yes, if you're doing something other than dying, it can make sense. – Jonathan Hall Nov 29 '11 at 01:07
  • I wouldn't call the standard error message useful. Compare with the one [provided by perl5i](http://p3rl.org/perl5i#Better-load-errors). – daxim Nov 29 '11 at 11:03
  • @daxim: I think it is useful... friendly on the other hand... it could use a fair amount of improvement in the friendly department. :) – Jonathan Hall Nov 29 '11 at 20:02