in reply to Modules sharing?

Here is a test that I set up that seems to be working, but I do not fully understand why. I removed the logging facility from module 1 and placed it into its own utility module. I'm confused in TestUtil.pm--why isn't redeclaring or reopening $LOG an issue? I assume the calls are entirely separate from each other? Even still, why are there no file conflicts?

test.pl
#!/usr/bin/perl use warnings; use strict; use TestMod1; use TestMod2; use TestUtil; print "in file.\n"; write_log('file');
TestMod1.pm
#!/usr/bin/perl package TestMod1; use warnings; use strict; use TestUtil; print "loaded Mod1\n"; write_log('Mod1'); 1;
TestMod2.pm
#!/usr/bin/perl package TestMod2; use warnings; use strict; use TestUtil; print "loaded Mod2\n"; write_log('Mod2'); 1;
TestUtil.pm
#!/usr/bin/perl package TestUtil; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(write_log); print "loading module TestUtil\n"; #our $LOG if not $LOG and print "LOG did not exist.\n"; our $LOG; open $LOG, '>', 'test.log' or die; print "\$LOG = $LOG\n"; sub write_log { my $string = shift; print $LOG "$string\n"; } 1;
test.log
Mod1 Mod2 file
screen output
loading module TestUtil $LOG = GLOB(0x4006fcd4) loaded Mod1 loaded Mod2 in file.

Replies are listed 'Best First'.
Re^2: Modules sharing?
by 5mi11er (Deacon) on Nov 08, 2005 at 19:49 UTC
    I'm hesitant about replying as I'm certainly no Perl internals guru. But, from the evidence you've provided in this example, one is forced to come to the conclusion that there is some magic involved with 'use' such that when using files multiple times, the resulting code is actually only loaded and run once.

    If this were not the case then you should have gotten several 'loading module TestUtil' lines, and several $LOG = GLOB(someaddress) lines. You didn't, so it works like you want it to. Be glad and rejoice.

    -Scott

      by george! you are correct. now i remember seeing an example of this process somewhere, how the compiler skips already-loaded modules. the print statements do make that quite obvious--thanks for pointing that out--hooray! :)