Question

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.
Was it helpful?

Solution

The require and import happen at runtime, whereas variables have to be declared at compile time. So we have three solutions:

  1. Import FindBin at compile time:

    use FindBin qw/$RealBin/;
    
    sub routine {
        say $RealBin;
    }
    

    I strongly suggest this solution.

  2. 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;
    }
    
  3. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top