tall_man has asked for the wisdom of the Perl Monks concerning the following question:

A person I work with refuses to use "use". He says that he read somewhere that if "use" is called twice on the same module, then the BEGIN blocks of that module are executed twice; for example, doing "use" twice on a database module will create two socket connections.

I have tried to convince him there is no essential difference between a "use Module qw(a b);" and:

BEGIN { require Module; Module->import(qw(a b)); }
I don't believe that either require or use will repeat BEGIN blocks of a module. Is there a definitive reference that would help to convince him?

Replies are listed 'Best First'.
Re: use and BEGIN
by blokhead (Monsignor) on Jul 19, 2003 at 20:04 UTC
    A simple test of his assumption should be enough to convince:

    foo.pm:

    package foo; BEGIN { print "foo's BEGIN\n"; } print "foo's body\n"; sub import { shift @_; print "foo's import: @_\n"; } 1;

    bar.pm:

    package bar; use foo qw(from bar); 1;

    test.pl:

    use lib '.'; use foo qw(from test.pl); use foo qw(from test.pl again); use bar;

    Output:

    $ perl test.pl foo's BEGIN foo's body foo's import: from test.pl foo's import: from test.pl again foo's import: from bar $
    BEGIN blocks are executed at compilation. use and require don't compile the same code twice.

    Look in perlvar under %INC for more info:

    The "require" operator uses this hash to determine whether a particular file has already been included.

    blokhead

Re: use and BEGIN
by tilly (Archbishop) on Jul 19, 2003 at 20:58 UTC
    In addition to the experiment already suggested, perldoc -f use and perldoc -f require (or referring to various htmlized versions of the core documentation) will confirm your understanding.
Re: use and BEGIN
by broquaint (Abbot) on Jul 20, 2003 at 12:55 UTC
    He says that he read somewhere that if "use" is called twice on the same module, then the BEGIN blocks of that module are executed twice
    Nope, just the import sub is called. The actual file being included isn't even touched on the second use as its existence has already been noted in %INC so that further proves that the BEGIN blocks are not touched. If written in pure perl use would look something like this
    use File::Spec::Functions; sub use { my($pkg, @args) = @_; my(@dirs, $file) = split '::', $pkg; my $path = catfile @dirs, "$file.pm"; return if exists $INC{$path}; my $fullpath = catfile( (grep { -f cafile($_, $path) } @INC)[0], $path ); my $code = IO::File->new($fullpath) or die "$!"; $INC{$path} = $fullpath; eval $code->getlines; $file->import(@args); }
    Of course it's missing the code references in %INC implementation, and it's totally untested, but it should give you some idea of how use actually works.
    HTH

    _________
    broquaint