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

Depending on what a user specifies, I want to include different perl modules (e.g. foo.pm bar.mk etc). I only want to include them if they haven't already been inclulded. So I may have a variable $module that contains the module specified. I want to do something like:

if (!defined(%$module::)) { eval { require "${module}.pm"; } }

Of course the above code doesn't work. Can someone help with this? Thanks,

Shannon Kerr

Replies are listed 'Best First'.
Re: check symbol table w/ dynamic name
by jwkrahn (Abbot) on Oct 17, 2006 at 04:32 UTC
    The names of modules that are loaded with require or use are stored in the %INC hash so if a module is already loaded it cannot be loaded again.

      This worked great. Thanks for this clean solution. So, here is what it will look like:

      if (!$INC{ "$module.pm" }) { eval { require "${module}.pm"; } }

      Thanks for this!

      Shannon Kerr
        The point is that perl already does the test when you require a module so your test is superfluous.

      if a module is already loaded it cannot be loaded again

      A minor nit-pick... a module can be re-loaded, if one is willing to do the requisite tomfoolery to make perl forget that it was already loaded.

Re: check symbol table w/ dynamic name
by ikegami (Patriarch) on Oct 17, 2006 at 05:15 UTC
    require already checks if the module has already been loaded before loading it again, so the following should work:
    my $module = 'Foo::Bar'; my $pm = $module; $pm =~ s{::}{/}g; $pm .= '.pm'; eval { require $pm } or die("Unable to load plugin $module: $@\n");

    Other solutions provided in this thread.

Re: check symbol table w/ dynamic name
by skerr1 (Sexton) on Oct 17, 2006 at 04:20 UTC

    The following seems to work:

    my $defd; eval ('$defd = defined(%'. $module .');'); if (!$defd)) { eval { require "${module}.pm"; } }

    I appreciate all ideas for this. Looking for the best solution.
    Thanks,

    Shannon Kerr