How can I “require” the Perl library, addressed by the path returned by the routine?

I can use this to include the a.pl file:

 require 'a.pl'; 

Or I can use this:

 $fn = 'a.pl'; require $fn; 

However, the subroutine will not work:

 sub fn { return 'a.pl'; } require fn(); # This is a syntax error 

Is there any syntax to resolve this? I noticed that I can get around the problem through

 sub fn { return 'a.pl'; } require eval("fn()"); 

... but it's not very pretty.

+5
source share
2 answers
 require(fn()); 

What a curious syntax error! The problem is adding an extra parenthesis to fix the error. Otherwise, the require PACKAGE form would seem to have priority over require EXPR , i.e. fn parsed as a simple designation for the module you want to load.

+8
source

The following may seem “modern,” but not correct enough / standard / POLA :

require fn->();

Or maybe an anonymous subroutine is more understandable / efficient:

 my $fn = sub { return "a.pl"; } ; require $fn->(); 
0
source

Source: https://habr.com/ru/post/1272533/


All Articles