Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use $variable

Status
Not open for further replies.

gnubie

Programmer
Apr 16, 2002
103
0
0
US
I want to use a variable for the use module. However, the following fails with a syntax error:

$modulename = "abc";
use $modulename;


Is it possible to use a variable? Other suggestions?

G.
 
Well, it looks like use doesnt accept an expression...it is however equivalent to:
Code:
BEGIN {
   $modulename="abc.pm"; 
   require $modulename;
}

and if you want to see the equivalent of use Module @list:

Code:
BEGIN {
   $modulename="abc.pm"; 
   require $modulename;
   import $modulename @list;
}
 
That'd work, but if you want the long way round, get your script to write another script, and call the new script afetr you close the old file

heh heh
;P

It's important in life to always strike a happy medium, so if you see someone with a crystal ball, and a smile on their face ...
 
gnubie, the reason for the behaviour you saw is that 'use' runs at compile time, so the variable hasn't yet been initialised, as that happens at run-time. Just to demonstrate:
Code:
#!/usr/bin/perl

print header();

use CGI qw(:standard);

Because 'use' is run at compile time, the above code will work perfectly, even though it seems that you're importing the CGI functions after you've attempted to call them.
 
no...that's not the problem because I even tried:

BEGIN{$modulename = "abc"}
use $modulename;

which would do the variable assignment prior to the use since begins and uses are both at compile time and happen in order of appearance. The 'use' just cant take an expression.

cge
 
Thanks for your comments and insight. It has been very helpful.

G.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top