On Aug 7, 11:18 am, [EMAIL PROTECTED] (Fermin Galan) wrote: > I'm trying to introduce conditional module loading in a Perl program, > but I'm experiencing problems. For example: > > if ($some_condition) { > use ModuleA; > (doing something using ModuleA)} > > else { > use ModuleB; > (doing something using ModuleB) > > } > > That is, if $some_condition is true then load the ModuleA, if false load > ModuleB. However, it doesn't seem to work this way and I've observed > (counterintuitively :)
It's perfectly intuitive, if you happen to understand what "use" actually does. ;-) perldoc -f use Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package. It is exactly equivalent to BEGIN { require Module; import Module LIST; } That is, use happens in a BEGIN block, which means it happens at compile-time, before the "if-else" structure is evaluated. > that both modules are always loaded (ModuleA and > ModuleB), no matter the value of $some_condition. Correct. Not only does $some_condition not have a value at the point when the "use" happens, Perl doesn't know or care that you might want to do something different based on that value. > Is it possible to do such "conditional module loading" in Perl? Yes. Either take the "use" out of the begin block: require ModuleA; import ModuleA; or use the 'if' pragma (which I don't like, as it forces you to put *other* code in a BEGIN{} block as well...) perldoc if Paul Lalli -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/