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

I am trying to do this, but I keep getting an error:

use $req_File;
$req_File is the result of a check.

the value of $req_File is in this format: Crypt::IDEA, Of course it is one of my personal Modules I created, but that is another story. If I just put use MyModule::Name;
then it works fine, but If I put what I have I get this error here:


Am I allowed to put a "use" with a Perl String?

If so, what am I doing wrong?
If not, I guess that is my problem ;o)

thx,
Richard

Replies are listed 'Best First'.
•Re: "use" file...
by merlyn (Sage) on Feb 08, 2003 at 17:29 UTC
    First, use is a compile-time operation, so hopefully, you have some way of getting the value early enough in the process. If not, you'll have to switch to require.

    Which brings me to the second point. You can't provide a variable string to use, but you can decompose it to its definition: a BEGIN block around a require and a method call:

    ## replace "use $string @imports" with: BEGIN { (my $filename = $string) =~ s,::,/,g; # unix/windows only require $filename; $string->import(@imports); }

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      The other approach is to
      BEGIN { eval "use $string \@imports; 1" or die "Failed lazy use(): $@"; }
      Er. pfaut already said this. Sorry. :-)

      Update:

      As merlyn said below. You need to be real careful that $string is completely under your control. You dont want to be reading it froma file for instance. At least not without some serious data cleaning first.

      --- demerphq
      my friends call me, usually because I'm late....

Re: "use" file...
by pfaut (Priest) on Feb 08, 2003 at 17:31 UTC

    'use' is parsed at compile time. Unless the 'use' statement and the assignment to $req_File are inside a BEGIN block, I would expect it to fail since no value has been assigned to $req_File. I'm not sure 'use' accepts a scalar as an argument. If you need the functionality of 'use' at runtime, use eval "use $req_File".

    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';