Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: use lib "."

by philipbailey (Curate)
on Aug 12, 2023 at 15:51 UTC ( [id://11153850] : note . print w/replies, xml ) Need Help??


in reply to use lib "."

I'm a bit surprised that nobody has so far mentioned FindBin, a core module, which is intended to solve your problem.

For your case, you can simply do:

use FindBin; use lib $FindBin::Bin;

The nice thing about FindBin is that as long as the directory structure of your code is constant, you can run scripts from wherever the directory tree exists. So it will work just as well from your local Git checkout, on the Jenkins server or the production location, which may well all be different.

A more typical directory structure would have a bin directory for scripts and lib for modules, so in that case the code would instead look like:

use FindBin; use lib "$FindBin::Bin/../lib";

Replies are listed 'Best First'.
Re^2: use lib "."
by kcott (Archbishop) on Aug 12, 2023 at 16:42 UTC
      Yes, FindBin has some global behaviours that don't work well in persistent environments where it could be use'd multiple times. But for simple cases like production or test scripts, there's no problem.
Re^2: use lib "."
by ikegami (Patriarch) on Aug 14, 2023 at 17:10 UTC

    This is the way, except that you should use $RealBin instead of $Bin. $Bin is buggy since it breaks when a symlink to the executable is used.

    In this case:

    use FindBin qw( $RealBin ); use lib $RealBin;

    When you have bin/ and lib/:

    use FindBin qw( $RealBin ); use lib "$RealBin/../lib";
Re^2: use lib "."
by Bod (Parson) on Aug 12, 2023 at 19:06 UTC
    I'm a bit surprised that nobody has so far mentioned FindBin, a core module, which is intended to solve your problem.

    ** slaps self round the face **

    Yes - I knew that I was missing something obvious and FindBin is that thing!!!

    I was aware of it but had completely forgotten about this simple solution!

    I've actually solved the issue by feeding lib an absolute path on the basis that the script cannot move without updating cron which has an absolute path. Given that the modules won't move anywhere else, this is probably a reasonable solution.