[Buffalo-pm] Test if module is loaded

Gianni, Andrew agianni at buffalo.edu
Tue Dec 8 11:13:20 PST 2009


Kevin is correct, in that you don't really need to worry about checking, as use and require do that for you. That said, the easiest way to check for a loaded package is to simply check for the definedness of %That::Package:: (not the extra set of ::). For example:

eval 'require That::Package' unless eval 'defined %That::Package::';
die $@ if $@ # check for eval error

if you dump %That::Package::, you'll see that it shows you all of the available data structures and methods/functions for that package space *if* it has already been required/used.

Andrew

> -----Original Message-----
> From: buffalo-pm-bounces+agianni=buffalo.edu at pm.org [mailto:buffalo-pm-
> bounces+agianni=buffalo.edu at pm.org] On Behalf Of Eye, Kevin
> Sent: Tuesday, December 08, 2009 1:08 PM
> To: Joshua Johnson
> Cc: Buffalo Perl Mongers
> Subject: Re: [Buffalo-pm] Test if module is loaded
> 
> All the "use" statements execute as the script is being read (compiled)
> and it won't actually run the code in them a second time. It's
> basically already doing the "if" statement you're trying to write.
> "require" is the same way -- it will only load/run it once (though at
> run-time). You need to use "do" to actually run a file more than once.
> You could verify all of this with a few test files and some print
> statements.
> 
> If you do really need to see if something has already been loaded you
> can look in the global/special variable %INC. To see if My::Module is
> loaded, check to see if $INC{'My/Module.pm'} is defined. Not sure why
> it is all translated that way (the /'s and :'s). Might be documented
> here: http://perldoc.perl.org/perlvar.html
> 
>  - Kevin
> 
> 
> 
> 
> On Dec 8, 2009, at 12:53 PM, Joshua Johnson wrote:
> 
> > Hello all!
> >
> > Is there a way to test if a perl module is loaded? I'm working on a
> > small project where I load some modules dynamically as part of a
> > configuration and then "use" them at that time. I don't get any
> errors
> > but I just feel dirty loading a module that may have already been
> > loaded. So, if at the top of the file I do:
> >
> > use Whatever::Project::MyStuff;
> >
> > Can I find out later if Whatever::Project::MyStuff is already loaded?
> > I suppose it may not matter or have any kind of performance impact
> but
> > now I'm just curious to know if it can be done.
> >
> > Thanks,
> > Josh J
> > _______________________________________________
> > Buffalo Perl Mongers Homepage
> > http://buffalo.pm.org
> >
> > Buffalo-pm mailing list
> > Buffalo-pm at pm.org
> > http://mail.pm.org/mailman/listinfo/buffalo-pm
> 
> _______________________________________________
> Buffalo Perl Mongers Homepage
> http://buffalo.pm.org
> 
> Buffalo-pm mailing list
> Buffalo-pm at pm.org
> http://mail.pm.org/mailman/listinfo/buffalo-pm


More information about the Buffalo-pm mailing list