http://www.perlmonks.org?node_id=798650

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

Monks

I have around 40 modules to load in a script, instead of hardcoding I want to load them dynamically (read the directory and use the modules)
I'm able to get the module names but the script throws an error when i do "use $fmodule"

Please point me to the right direction. Below is the sample script
#!/usr/bin/perl use strict; use warnings; use File::Basename; BEGIN { my $path = '/path/ABC/*.pm'; my @files = < $path >; foreach my $mod(@files){ my($filename, $directories, $suffix) = fileparse($mod); $filename=~s/\.pm//gx; use $filename; } }
I get the following error when the script is executed
syntax error at t.pl line 13, near "use $filename" BEGIN not safe after errors--compilation aborted at
Please let me know the correct way of loading the modules.

Replies are listed 'Best First'.
Re: Dynamically load all modules from a directory
by toolic (Bishop) on Oct 01, 2009 at 13:36 UTC
    Try require instead of use, whose documentation states "that Module must be a bareword".
      Thanks everyone for your valuable comments.
      I looked at Module::Pluggable, read the docs and implemented it right away.

      And my impressions?? the module rocks and fits to my needs perfectly.

      Thank you once again.
        +1
Re: Dynamically load all modules from a directory
by Fletch (Bishop) on Oct 01, 2009 at 14:34 UTC

    Module::Pluggable may be of interest.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Dynamically load all modules from a directory
by ELISHEVA (Prior) on Oct 01, 2009 at 15:27 UTC

    use needs a bare word so it isn't suitable for the kind of dynamic loading you want to do. require can be used instead but you must use the file name as is (don't strip the final .pm) like this:

    foreach my $mod(@files){ my($filename, $directories, $suffix) = fileparse($mod); # don't do this - we need the actual filename!!! # $filename=~s/\.pm//gx; require $filename; }

    There is a nice example in the perl documentation for require as well.

    Best, beth

Re: Dynamically load all modules from a directory
by jakobi (Pilgrim) on Oct 01, 2009 at 13:38 UTC

    ok, just pointing as requested:

    use strict; use warnings; # eval{} is insufficient - we need string-extrapolation BEGIN { my $f="Data::Dumper"; eval "use $f"; }; my $g="a string"; print "Dumper", Dumper($g),"\n";

    Update: Beth - this does do dump :)