How do I use a Perl package known only in runtime?

后端 未结 7 527
忘掉有多难
忘掉有多难 2020-12-10 02:21

I have a Perl program, that needs to use packages (that I also write). Some of those packages are only chosen in Runtime (based on some environment variable). I don\'t want

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 03:08

    Many years later, eval "use $mod_name"; seems to work just fine (as of at least 5.8.8).

    The advantage over eval "require $mod_name"; is that the loaded module's default exports are automatically imported; in other words:

    eval "use $mod_name";

    is the shorter equivalent of

    eval "require $mod_name"; $mod_name->import();

    Here's a test command, which passes the name of the module via env. variable mod_name, loads and imports the module, then uses an imported function (assumes a POSIX-like shell):

     $ mod_name='Data::Dumper' perl -e 'eval "use $ENV{mod_name}"; print Dumper("hi!")'
     $VAR1 = 'hi!';
    

    I may be missing subtleties; if so, please let me know.

提交回复
热议问题