简体   繁体   中英

How can I 'require' a Perl library addressed by a path returned by a subroutine?

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

require 'a.pl';

Or I can use this:

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

However, a subroutine won't work:

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

Is there a syntax for allowing this? I noticed that I can work around the issue via

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

...but that's not terribly pretty.

require(fn());

What a curious syntax error! Adding an extra parenthesis to disambiguate precedence fixes the problem. It seems that otherwise the require PACKAGE form would have precedence over require EXPR , ie the fn is parsed as the bareword designating the module you want to load.

The following may appear "modern" but not sufficiently correct/standard/ POLA :

require fn->();

Or maybe an anonymous subroutine is more readable/efficient in some way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM