Frerich Raabe
Frerich Raabe

Reputation: 94279

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.

Upvotes: 5

Views: 76

Answers (2)

G. Cito
G. Cito

Reputation: 6378

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->();

Upvotes: 0

amon
amon

Reputation: 57590

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, i.e. the fn is parsed as the bareword designating the module you want to load.

Upvotes: 8

Related Questions