0

I am wokring on a perl project and i have to dynamically use perl modules. I have the following module called CT.pm:

sub new {
    my $class = shift;
    my ($debug, $debug_matches,%checkHash) = @_;
    my $self = {};
    $self->{DEBUG} = shift;
    $self->{DEBUG_MATCHES} = shift;
    $self->{CHECKRESULT_OK} = "COMPLIANT"; 
    $self->{CHECKRESULT_ERROR} = "NONCOMPLIANT"; 
    %{$self->{checkHash}} = %checkHash;

    eval{
        use $checkHash{"type"};
        $check = $checkHash{"type"}->new($self->{DEBUG},$self->{DEBUG_MATCHES},%checkHash);
    };

    bless($self,$class);
    return $self;
}

This constructor gets a hash called %checkHash as parameter. This hash has a key called type. The value that this key maps to a name of a perl module i want to use dynamically.

I have come up with the following way to do it:(which i know wont work and i also know that people say that eval is bad):

eval{
    use $checkHash{"type"};
    $check = $checkHash{"type"}->new($self->{DEBUG},$self->{DEBUG_MATCHES},%checkHash);
};

But the idea is to dynamically use a perl module with the name of $checkHash{"type"}.

If anyone has any idea on how to do this pls help :) thx! :D

Diemauerdk
  • 5,238
  • 9
  • 40
  • 56
  • Found a way of doing it - cant post any solutions within 8 hours. – Diemauerdk May 02 '12 at 07:38
  • 2
    This has been discussed before: http://stackoverflow.com/questions/251694/how-can-i-check-if-i-have-a-perl-module-before-using-it http://stackoverflow.com/questions/1094125/try-to-use-module-in-perl-and-print-message-if-module-not-available http://stackoverflow.com/questions/1917261/how-can-i-dynamically-include-perl-modules http://stackoverflow.com/questions/2855207/how-do-i-load-a-module-at-runtime http://stackoverflow.com/questions/3470706/perl-dynamically-include http://stackoverflow.com/questions/3945583/how-can-i-conditionally-use http://stackoverflow.com/questions/6855970/use-of-eval – daxim May 02 '12 at 08:26

1 Answers1

2

Your eval is a "block eval" and is actually just an exception catching mechanism in Perl, lacking any stigma associated with usual "string eval". You can dynamically load modules with string eval via eval "require $checkHash{'type'}". If you wish to avoid using string eval at all, all you need is just to manually transform bareword module name to .pm file path. You still should use block eval to catch module loading exceptions:

my $file = $class . '.pm';
$file =~ s{::}{/}g;
eval { require $file };
if($@){ die "failed to load $class: $@" }

This still won't run loaded class import method. You'll need to break class path to pieces and find it manually. This also most often can be safely skipped for OO classes.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68