简体   繁体   中英

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

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 Dumper is already imported when the line of its usage gets compiled.

You can read more about BEGIN blocks here: perlmod

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM