Liviu Popescu
Liviu Popescu

Reputation: 73

Perl load module BEGIN

I have this code

print "Starting\n";
BEGIN {
        $module='Data::Dumper';
        $module_available=1;
        eval "use $module; 1" or $module_available = 0;
        }
$var=1;
print "Module=$module_available\n";
print Dumper $var if ($module_available==1);

and the output is

Starting
Module=1
$VAR1 = 1;

and this

print "Starting\n";
        $module='Data::Dumper';
        $module_available=1;
        eval "use $module; 1" or $module_available = 0;
$var=1;
print "Module=$module_available\n";
print Dumper $var if ($module_available==1);

and the output

Starting
Module=1

Why on the first scenario the variable is printed

Upvotes: 2

Views: 156

Answers (1)

clamp
clamp

Reputation: 3262

You should always

use strict;
use warnings;

In your second example, when your code is compiled, Dumper is not known as a function. So perl treats it as a bareword filehandle. If you use warnings, you get

print() on unopened filehandle Dumper at file.pl line 10. 

In the first example you wrap the eval in a BEGIN block. So Dumperis already imported when the line of its usage gets compiled.

You can read more about BEGIN blocks here: perlmod

Upvotes: 6

Related Questions