Reputation: 25107
This doesn't work (error messages below). How could I make this work?
#!/usr/bin/env perl
use warnings;
use strict;
use 5.10.1;
sub routine {
require FindBin;
FindBin::->import( '$RealBin' );
say $RealBin;
}
routine();
Gives this output
Global symbol "$RealBin" requires explicit package name at ./perl.pl line 9.
Execution of ./perl.pl aborted due to compilation errors.
Upvotes: 3
Views: 921
Reputation: 57590
The require
and import
happen at runtime, whereas variables have to be declared at compile time. So we have three solutions:
Import FindBin
at compile time:
use FindBin qw/$RealBin/;
sub routine {
say $RealBin;
}
I strongly suggest this solution.
Declare the variable so that it can be used without strict
or warnings
complaining:
sub routine {
require FindBin;
FindBin->import('$RealBin');
our $RealBin; # this just declares it so we can use it from here on
say $RealBin;
}
Don't import the symbol and use the fully qualified name instead:
sub {
require FindBin;
# FindBin->import; # does nothing here
say $FindBin::RealBin;
}
Loading FindBin
at runtime is probably useless from a performance perspective, and you should just use
it normally. If you are doing these weird run-time gymnastics to calculate the $RealBin
anew at each call of routine
, none of these solutions will work because require
does not execute the module if it has already been loaded (it does something like $INC{'FindBin.pm'} or return
). The FindBin::again
function might help instead.
Upvotes: 11