in reply to Are dynamic 'use' statements possible?

The following snippet avoids all the manual module->filename munging. (An interesting property is the nesting of several compile- and execution phases..)
BEGIN { my $m = "File::Spec::Functions"; eval "use $m;" } print catfile qw(a b c);
____________
Makeshifts last the longest.

Replies are listed 'Best First'.
This works, but at what cost...?
by tosh (Scribe) on Jul 02, 2002 at 22:18 UTC
    This seems to be exactly the solution I'm after, however I wonder about the consequences in a mod_perl context...

    Say I have a module called DO_STUFF.pm, and DO_STUFF has the following code in it:
    package DO_STUFF.pm; BEGIN { use strict; use Exporter; use vars qw(@ISA @EXPORT); my $conf = determine_conf_module_name(); eval "use $conf;"; } do_stuff....etc...
    Now I load DO_STUFF.pm into memory for mod_perl and at loading time I would assume that $conf is determined and that module is now loaded into memory space for use by DO_STUFF.

    But what happens when I am using DO_STUFF in a context that changes what determine_conf_module_name() returns, i.e. a new $conf, how would DO_STUFF.pm (already loaded into memory) know to use a different module?

    Would it be better to execute
    my $conf = determine_conf_module_name(); eval "use $conf;";
    during instantiation, like this:
    package DO_STUFF.pm; use strict; use Exporter; use vars qw(@ISA @EXPORT); ... sub new { my $conf = determine_conf_module_name(); eval "use $conf;"; ... }
    Or is the BEGIN{} block run only during instantiation of the object so I'm fine...?

    oooOOOOooo....my head is all twisty now...

    THANKS ALL!!!

    Tosh

      Oh la la.

      To answer your questions, yes, BEGIN {} only execute once when the module is compiled, and yes, you can use eval "use $module;"; in your new(). However (!!), how is your configuration module set up? Do you import variables into your own namespace from it? Or do the configuration modules share one namespace? In that case, loading a configuration module would affect all instances of your class.. and you're looking at a major mess.

      Is there any reason you can't simply use an honest to god configuration file with something like Config::Inifiles, or at least my $config = do "config_in_anonymoushash.pl";?

      Makeshifts last the longest.