rmarimon rmarimon -4 years ago 87
Perl Question

Load and use perl module without knowing the module name but knowing the file name

I have been toying with the modulino perl pattern and would like to load one without knowing the package name and only the file in which it is. I'm looking for something that could be used like this:

eval {
my $file = "some-file-name-in-the-hierarchy-unrelated-to-package-name";
my $module = something($file);

here is the key. No
since I would need the module name afterwards. Do I have to read the
and parse the
name out of it to then use it? There might a better way I'm sure. There always is in perl.

Answer Source

Which of the files do you control? If you are creating the program as a modulino and then trying to load that file, just make the last statement in the file return the package name. require expects you to return a true value and most modules use 1;. However, you can use any true value you like. This will be the return value of require:

# i_dont_know_whats_inside
package Buster;


Loading it is easy:

my $package = require 'i_dont_know_whats_inside';

print "Package is $package\n";

$package->new( ... );

If you can't control the file you're loading, it's not that hard to find out what's inside:

my @packages = load_file( 'i_dont_know_whats_inside' );

print "Packages are @packages\n";

sub load_file {
    my $file = shift;
    require Module::Extract::Namespaces;
    my @packages = Module::Extract::Namespaces->from_file( $file );
    my $rc = require $file;
    return @packages;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download