R – Why can’t I use an expression to build a class name in Perl’s require


Suppose the module AAA::BBB::CCC located in ~/modules/AAA/BBB/CCC.pm,
and "~/modules" is in @INC, so why the following code doesn't work and lead to compile error?

$class = "AAA::BBB" ;
$type = "CCC";
require $class . '::' . $type ;

I try to use require AAA::BBB::CCC instead, it works . If I do need dynamically require a module by combining strings together rather than hardcode the module name directly, how should I do ?


Best Solution

My approach:

my $class = "AAA::BBB";
my $type = "CCC";

my $full_class_name = $class . '::' . $type;
( my $file_name = $full_class_name . '.pm' ) =~ s{::}{/}g;

require $file_name;


Using eval, if you're only doing "die $@ if $@" doesn't make much sense - without eval it will work just as fine.

This additional step of making file_name, and requiring $file_name instead of class makes it not required to use string based eval, which tends to be rather slow.

Of course you still can use eval if you want to provide some kind of fallback:

eval { require $file_name };
if ( my $error = $@ ) {
    ... do something ...

But note, that this is block-based eval, and not a string-based one.

Related Question