How can I conditionally use a module in Perl?

Viewed 14307

I want to do something like this in Perl:

$Module1="ReportHashFile1"; # ReportHashFile1.pm
$Module2="ReportHashFile2"; # ReportHashFile2.pm

if(Condition1)
{
  use $Module1;
}
elsif(Condition2)
{
  use $Module2;
}

ReportHashFile*.pm contains a package ReportHashFile* .

Also how to reference an array inside module based on dynamic module name?

@Array= @$Module1::Array_inside_module;

Is there anyway I can achieve this. Some sort of compiler directive?

4 Answers

Maybe helpful...

A little example for debugging.

sub DEBUG () {1};               # It's the condition (may be a debuglevel...)

use if DEBUG, Data::Dumper;     # Conditionally load

my $testvar = "foo";
print "Testing: $testvar\n" if     DEBUG;
print "No testing\n"        unless DEBUG;

print Dumper \$testvar if DEBUG;  # "Dumper" only available if "DEBUG" returns "true".

Output with sub DEBUG () {1};

Testing: foo
$VAR1 = \'foo';

Output with sub DEBUG () {0};

No testing

q.v. perldoc.perl.org/if

Related