PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 25, 2022

[FIXED] How can I conditionally use a module in Perl?

 August 25, 2022     conditional, include, module, perl     No comments   

Issue

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?


Solution

You might find the if module useful for this.

Otherwise the basic idea is to use require, which happens at run-time, instead of use, which happens at compile-time. Note that '

BEGIN {
    my $module = $condition ? $Module1 : $Module2;
    my $file = $module;
    $file =~ s[::][/]g;
    $file .= '.pm';
    require $file;
    $module->import;
}

As for addressing globals, it might be easier if you just exported the variable or a function returning it to the caller, which you could use by its unqualified name. Otherwise there's also the possibility of using a method and calling it as $Module->method_name.

Alternatively, you could use symbolic references as documented in perlref. However, that's usually quite a code smell.

my @array = do {
    no strict 'refs';
    @{ ${ "${Module}::Array_inside_module" } };
};


Answered By - rafl
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing