Simon Dirmeier Simon Dirmeier -4 years ago 128
Perl Question

Prevent multiple inclusions in perl

Suppose I have two files: a module file that looks like this:

package myPackage;
use Bio::Seq;


and another file that looks like this:

use lib "path/to/lib";
use myPackage;
use Bio::Seq;


How can i prevent that Bio::Seq is included twice? Thanx

Answer Source

use Foo

is mostly equivalent to


# perldoc -f use
BEGIN { 
    require "Foo.pm";
    Foo->import();
}

And require "Foo" is mostly equivalent to


# perldoc -f require
sub require {
  my ($filename) = @_;
  if (exists $INC{$filename}) {
    return 1 if $INC{$filename};
    die "Compilation failed in require";
  }
  # .... find $filename in @INC
  # really load
  return do $realfilename;
}

So

No, the code won't be "Loaded" more than once, only "imported" more than once.

If you have code such as



package Bio::Seq;
...
sub import { 
  # fancy stuff
}

And you wanted to make sure a library was loaded, but not call import on it,


#perldoc -f use
use Bio::Seq ();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download