Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "use lib" the appropriate directory depending on installation location?

Tags:

perl

I have an object-oriented web-app that is installed in multiple locations on my server. Once for "live", once for "beta", etc. Being object-oriented, it consists of many perl modules. In the main module, I must "use lib" the appropriate directory for all of the custom perl modules for that instance of the app.

This is no big deal, I have a BEGIN block that checks the location of the main program and sets the library directory appropriately. However I also have a lot of utility, command line programs that need to do the same thing. I don't want to cut and paste this code everywhere.

What is the best way to share this code snippet amongst the various programs that need it?

I can't "use" it because the libary path isn't set up yet. Maybe "do" or "require" would the be the right answer, but both of those will search @INC, which is inappropriate.

Maybe something like eval `cat GetLib.pl`; would be appropriate but it seems kind of clunky and fragile.

Here is the BEGIN block that I currently use:

BEGIN {
  use FindBin qw ($Bin);
  require lib;

  if ($Bin =~ /^\/home\/w\/myapp_live/) {
    lib->import('/home/w/myapp_live/lib');
    print STDERR "live site\n";
  }

  if ($Bin =~ /^\/home\/w\/myapp_beta/) {
    lib->import('/home/w/myapp_beta/lib');
    print STDERR "beta site\n";
  }

  if ($Bin =~ /^\/home\/w\/myapp_test/) {
    lib->import('/home/w/myapp_test/lib');
    print STDERR "testing site\n";
  }

}

Thank you!

like image 823
NXT Avatar asked Nov 11 '09 00:11

NXT


1 Answers

FindBin::libs is excellent for that. I've used it for a while in a large system with no problems at all.

The default invocation looks like it'll work for you, simply:

use FindBin::libs;

This will search for all the ./lib dirs in all the parent directories of the current file's dir and use lib them. So, for example, if your script lives in /home/w/myapp_live/scripts/defurblise_widgets.pl (and use()es FindBin::libs), it will look for:

/home/w/myapp_live/scripts/lib
/home/w/myapp_live/lib
/home/w/lib
/home/lib
/lib       # (presumably!)

Any that it finds with be added to you @INC with use lib.

But, if that's not quite what you need, it's a very flexible module. I'd be surprised if you can't find a way to make it do what you want.

like image 146
Dan Avatar answered Nov 07 '22 07:11

Dan