in reply to module location

That's because the assigment of $perl_module doesn't happen until runtime, while the use happens at compile time.

You basically have two options:

Move assignement to compile time
my $perl_module; BEGIN {$perl_module = shift}; eval "use $perl_module";

Move loading of module to runtime
(my $filename = "$perl_module.pm") =~ s#::#/#g; require $filename; $perl_module->import;

The first has the disadvantage that you need to eval a string. If you can't trust the parameter input, that may be a security issue.

The latter has the disadvantage that you must convert the module name to a filename. But you need the original module name to be able to do the import().

Hope this helps.

Liz

Replies are listed 'Best First'.
Re: Re: module location
by hmerrill (Friar) on Nov 07, 2003 at 15:43 UTC
    This is driving me nuts - I don't understand why this doesn't work:
    #!/usr/bin/perl -w use strict; my $perl_module; BEGIN { my $ct_args = @ARGV; if ($ct_args != 1) { print "\nUsage: pwhich_short <perl module name>\n\n"; print "Example: pwhich_short DBI\n\n"; exit; } $perl_module = shift; }; eval "use $perl_module" or die "Can't find $perl_module: $!\n";
    This code gets this error:
    Can't find DBI:
    That's it. Does this work for you? Any ideas?

    Thanks.
      I think you want to replace:
      eval "use $perl_module" or die "Can't find $perl_module: $!\n";
      by:
      eval "use $perl_module"; die "Can't find $perl_module: $@\n" if $@;

      Eval just returns whatever was returned by use, which to my knowledge is undefined (please someone correct me if I'm wrong).

      You need to check whether $@ is non-empty after the eval().

      Liz

        Liz, you get the gold star! It works - I've used eval before, but mostly just in DBI transaction code where I had an eval block({}) and then checked $@ after, but I guess I forgot that for *any* eval errors you need to check $@. Thank you very much!

        Hardy