FindBin::libs(3pm)

πŸ“¦
version 4.0.4 Β· 3 versions
, in ubuntu resolute, ubuntu stonking

🌸 FindBin::libs 🌸

User Contributed Perl Documentation Β· 3pm

okay bestie, welcome to the page for FindBin::libs from the Perl docs (section 3pm) πŸ’– this one is genuinely iconic, it's the thing that stops you from hardcoding use lib paths in every single script you own. let's get into it πŸ¦‹


✨ NAME ✨

FindBin::libs β€” locate and a use lib or export directories based on $FindBin::Bin.


✨ SYNOPSIS ✨

so the entire vibe here is: one line at the top of your script and it goes hunting up the tree for lib dirs. here's the whole tour 🫢

# search up $FindBin::Bin looking for ./lib directories
# and "use lib" them.

use FindBin::libs;

and if you're the type who likes writing the defaults down on purpose (respect):

# same as above with explicit defaults.

use FindBin::libs qw( base=lib use=1 noexport noprint );

want to see the dirs before they get used? πŸ’…

# print the lib dir's before using them.

use FindBin::libs qw( print );

different dir name, same energy:

# find and use lib "altlib" dir's

use FindBin::libs qw( base=altlib );

start somewhere else entirely:

# move starting point from $FindBin::Bin to '/tmp'

use FindBin::libs qw( Bin=/tmp base=altlib );

skip the use lib and just get an array instead:

# skip "use lib", export "@altlib" instead.

use FindBin::libs qw( base=altlib export );

both at once? not mutually exclusive bestie:

# find altlib directories, use lib them and export @mylibs

use FindBin::libs qw( base=altlib export=mylibs use );

export defaults to nouse, so these two are literally the same thing:

# "export" defaults to "nouse", these two are identical:

use FindBin::libs qw( export nouse );
use FindBin::libs qw( export       );

and use + export are absolutely allowed to coexist, pick your combo:

# use and export are not exclusive:

use FindBin::libs qw( use export            ); # do both
use FindBin::libs qw( nouse noexport print  ); # print only
use FindBin::libs qw( nouse noexport        ); # do nothting at all

want the tea β˜• about what it actually found:

# print a few interesting messages about the
# items found.

use FindBinlibs qw( verbose );
πŸ‘€ yes, that one is spelled exactly like that in here. not me editing it. keeping it 100% as-is.

turn on a breakpoint after the args get processed, before any search/export/use lib happens:

# turn on a breakpoint after the args are prcoessed, before
# any search/export/use lib is handled.

use FindBin::libs qw( debug );

prefix PERL5LIB with the lib's found:

# prefix PERL5LIB with the lib's found.

use FindBin::libs qw( perl5lib );

and here's the subdir situation β€” finding a subdir of the lib's you're looking for:

# find a subdir of the lib's looked for.
# the first example will use both ../lib and
# ../lib/perl5; the second ../lib/perl5/frobnicate
# (if they exist). it can also be used with export
# and base to locate special configuration dir's.
#
# subonly with a base is useful for locating config
# files. this finds any "./config/mypackage" dir's
# without including any ./config dir's. the result
# ends up in @config (see also "export=", above).

use FindBin::libs qw( subdir=perl5 );

use FindBin::libs qw( subdir=perl5/frobnicate );

use FindBin::libs qw( base=config subdir=mypackage subonly export );

base + subonly also carry when your project lives in multiple git repos:

# base and subonly are also useful if your
# project is stored in multiple git
# repositories.
#
# say you need libs under api_foo/lib from api_bar: a
# base of the git repository directory with subdir of
# lib and subonly will pull in those lib dirs.

use FindBin::libs qw( base=api_foo subdir=lib subonly );

and there is zero harm in using it multiple times to stack up layers of libs:

# no harm in using this multiple times to use
# or export multiple layers of libs.

use FindBin::libs qw( export                                            );
use FindBin::libs qw( export=found base=lib                             );
use FindBin::libs qw( export=binz  base=bin            ignore=/foo,/bar );
use FindBin::libs qw( export=junk  base=frobnicatorium                  );
use FindBin::libs qw( export       base=foobar                          );

✨ DESCRIPTION ✨

🌸 General Use 🌸

so the whole deal: this module walks the path up to $FindBin::Bin and either use libs the directories it finds, or hands them back to you as an array. the default is to locate lib directories and use lib them, with no printing of the list. simple, clean, slay ✨

the options control whether the lib's found get exported into the caller's space, exported to PERL5LIB, or printed. and here's the lil gotcha: exporting or setting perl5lib will turn off the default use lib, so that:

use FindBin::libs qw( export );
use FindBin::libs qw( p5lib  );

are equivalent to

use FindBin::libs qw( export nouse );
use FindBin::libs qw( p5lib  nouse );

combining export with use or p5lib may be useful. p5lib and use together are probably not all that useful. πŸ’€

πŸŽ€ Alternate directory name: 'base' πŸŽ€

the basename it searches for can be changed via base=name, so that

use FindBin::libs qw( base=altlib );

will search for directories named altlib and use lib them. πŸ¦‹

πŸŽ€ Exporting a variable: "export", "scalar", "append" πŸŽ€

πŸ’… "export" πŸ’…

this installs the results of locating directories into the caller's space. without any argument, export pushes out a variable named after the located [sub]dir; an argument can be supplied to give the variable name. without the scalar option, the exported variable will be an array in increasing order of distance (i.e., up the file tree); with the scalar option only the first (i.e., nearest) path is exported.

if export is given then nouse is assumed; using both leaves the variable exported and its contents handed to use lib.

for example:

use FindBin::libs qw( export );

will find lib directories and export @lib with the list of directories found.

use FindBin::libs qw( export=mylibs );

will find lib directories and export them as @mylibs to the caller.

if export only is given then the use option defaults to false. so:

use FindBin::libs qw( export );
use FindBin::libs qw( export nouse );

are equivalent. this is mainly for use when looking for data directories with the base= argument.

if base is used with export the default array name is the base directory value:

use FindBin::libs qw( export base=meta );

exports @meta while

use FindBin::libs qw( export=metadirs base=meta );

exports @metadirs as a list of paths ending in /meta.

the use and export switches are not exclusive:

use FindBin::libs qw( use export=mylibs );

will locate lib directories, use lib them, and export @mylibs into the caller's package. best of both worlds, honestly πŸ‘‘

πŸ’… "scalar" πŸ’…

only searches for the first directory, which is exported (or overwritten) as a scalar rather than array. for example, if a project directory has ./bin and ./etc dir's then #! code in bin with

use FindBin::libs qw( export scalar base=etc );

will have an $etc variable with the absolute path to ./bin/../etc. for configuration variables this is usually what you want and allows for $etc/Foo.conf rather than $etc[0]/Foo.conf. so much cleaner fr fr πŸŽ€

πŸ’… "append" πŸ’…

sometimes it's simpler to accumulate multiple searches into a single array. say for ./etc dir's in collection of standard locations.

in that case:

use FindBin::libs qw( export=etc base=foo subdir=etc );
use FindBin::libs qw( export=etc base=bar subdir=etc append );

produces something like

(
    /path/to/foo/etc
    /path/to/bar/etc
)

without append @etc will have only ./bar/etc since the array would be overwritten with each call to import. 😭

πŸŽ€ Subdirectories πŸŽ€

the subdir and subonly settings will add or exclusively use subdir's. this is useful if some of your lib's are in ../lib/perl5 along with ../lib or all of the lib's are in ../lib/perl5.

these could be handled with:

use FindBin::libs;
use FindBin::libs qw( subdir=perl5 subonly );

which uses the lib dir's along with any lib/perl5 dirs.

this can also be handy for locating subdir's used for configuring packages:

use FindBin::libs qw( export base=config subonly=mypackage );

will leave @config containing any mypackage dir's found up the tree, nearest to closest.

the array format is convienent for locating configuration files shared between projects in separate, sibling directories. for example given:

./proj/Foo/etc
./proj/etc

with

use FindBin::libs qw( export subdir=etc subonly )

will export @etc with qw( ../proj/Foo/etc ../proj/etc ) in lexical order by distance from the #! code. at that point

use List::Util qw( first );

my $path = first { -e "$_/Global.config" } @etc;

will locate the nearest Global.confg file. note that this is not the same as using scalar since that will export $etc with only ./Foo/etc. 🧚

πŸŽ€ Setting PERL5LIB: p5lib πŸŽ€

for cases where the environment is more useful for setting up library paths p5lib can be used to preload this variable. this is mainly useful for automatically including directories outside of the parent tree of $FindBin::bin.

for example, using:

$ export PERL5LIB="/usr/local/foo:/usr/local/bar";

$ myprog;

or simply

$ PERL5LIB="/usr/local/lib/foo:/usr/lib/bar" myprog;

(depending on your shell) with #! code including:

use FindBin::libs qw( p5lib );

will not use lib any dir's found but will update PERL5LIB to something like:

/home/me/sandbox/branches/lib:/usr/local/lib/foo:/usr/lib/bar

this can make controlling the paths used simpler and avoid the use of symlinks for some testing (see examples below). 🌈

🌈 Skipping directories 🌈

by default, lib directories under / and /usr are sliently ignored. this normally means that /lib, /usr/lib, and '/usr/local/lib' are skipped. the ignore parameter provides a comma-separated list of directories to ignore:

use FindBin::libs qw( ignore=/skip/this,/and/this/also );

will replace the standard list and thus skip /skip/this/lib and /and/this/also/lib. it will search /lib and /usr/lib since the argument ignore list replaces the original one. ⚠️ so like, heads up, you're swapping the whole list out, not adding to it.

🌈 Homegrown Library Management 🌈

an all-too-common occurrence managing perly projects is being unable to install new modules becuse "it might break things", and being unable to test them because you can't install them. the usual outcome of this is a collection of hard-coded

use lib qw( /usr/local/projectX ... )

code at the top of each #! file that has to be updated by hand for each new project. 😭 the pain is real.

to get away from this you'll often see relative paths for the lib's, which require running the code from one specific place. all this does is push the hard-coding into cron, shell wrappers, and begin blocks. πŸ’€

with FindBin::libs you need suffer no more.

automatically finding libraries in and above the executable means you can put your modules into cvs/svn and check them out with the project, have multiple copies shared by developers, or easily move a module up the directory tree in a testbed to regression test the module with existing code. all without having to modify a single line of code. πŸ’– iconic behaviour, genuinely

Code-specific modules πŸ’…

Okay bestie, picture this: your sandbox lives in ./sandbox and right now you're chilling in ./sandbox/projects/package/bin working on a perl executable. You might have some modules that are specific β€” or customized β€” just for this package, some modules you share within the project, and maybe company-wide modules that get managed out of ./sandbox while you're in development. All of that lives under a ./qc tree on the test boxes and under ./production on the production servers. πŸ—οΈ

To keep it simple, say your sandbox lives in your home directory, /home/jowbloe, either as a directory or a symlink.

If your #! line uses FindBin::libs in it, then it will effectively do this:

use lib
qw(
    /home/jowbloe/sandbox/lib
    /home/jowbloe/sandbox/project/lib
    /home/jowbloe/sandbox/project/package/lib
);

…if you run /home/jowbloe/sandbox/project/package/bin/foobar. And this happens the exact same way whether you use a relative or absolute path, perl -d the thing, or if any of the lib directories are symlinks pointing outside your sandbox. ✨

Which means the most specific module directories ("closest" to your executable) get picked up first. periodt.

So if you've got a version of Frobnicate.pm in your ./package/lib with modifications, that's totally fine: you'll use it before the one in ./project or ./sandbox. πŸ‘‘

Using the p5lib argument can help in cases where some of the code lives outside of the sandbox. To test a sandbox version of some other module:

use FindBin::libs qw( p5lib );

and

$ PERL5LIB=/other/sandbox/module foobar;

Regression Testing πŸ§ͺ

Eventually, though, you'll need to regression test Frobnicate.pm with other modules.

Fine: move, copy, or symlink it into ./project/lib and you can merrily run ./project/*/bin/* with it and see if there are any problems. In fact, so can the nice folks in QC. πŸ’–

If you want to install and test a new module, just prefix it into, say, ./sandbox/lib and all the code that has FindBin::libs will simply use it first. no cap.

$FindBin::Bin is relative to where an executable is started from. This allows a symlink to change the location of directories used by FindBin::libs. Full regression testing of an executable can be accomplished with a symlink:

./sandbox
    ./lib -> /homegrown/dir/lib
    ./lib/What/Ever.pm

    ./pre-change
        ./bin/foobar

    ./post-change
        ./lib/What/Ever.pm
        ./bin/foobar -> ../../pre-last-change/bin/foobar

Running foobar symlinked into the post-change directory will test it with whatever collection of modules is in the post-change directory. A large regression test on some collection of changed modules can be performed with a few symlinks into a sandbox area. iconic tbh. 🌈

Managing Configuration and Meta-data Files πŸŽ€

The base option alters FindBin::libs standard base directory. This allows for a hierarchical set of metadata directories:

./sandbox
    ./meta
    ./project/
        ./meta

    ./project/package
        ./bin
        ./meta

with

use FindBin::libs qw( base=meta export );

sub read_meta
{
    my $base = shift;

    for my $dir ( @meta )
    {
        # open the first one and return
        ...
    }

    # caller gets back empty list if nothing was read.

    ()
}

using "prove" with local modules. 🌸

Modules that are not intended for CPAN will not usually have a Makefile.PL or Build setup. This makes it harder to check the code via "make test". Instead of hacking a one-time Makefile, FindBin::libs can be used to locate modules in a "lib" directory adjacent to the "t: directory. The setup for this module would look like:

./t/01.t
./t/02.t
...

./lib/FindBin/libs.pm

since the *.t files use FindBin::libs they can locate the most recent version of code without it having to be copied into a ./blib directory (usually via make) before being processed. If the module did not have a Makefile this would allow:

prove t/*.t;

to check the code. slay. 🫢


Notes πŸ“

Alternatives πŸ’­

FindBin::libs was developed to avoid pitfalls with the items listed below. As of FindBin::libs-1.20, this is also mutli-platform, where other techniques may be limited to *NIX or at least less portable.

PERL5LIBS

PERL5LIB can be used to accomplish the same directory lookups as FindBin::libs. The problem is PERL5LIB often contains absolute paths and does not automatically change depending on where tests are run. This can leave you modifying a file, changing directory to see if it works with some other code and testing an unmodified version of the code via PERL5LIB. FindBin::libs avoids this by using $FindBin::bin to reference where the code is running from.

The same is true of trying to use almost any environmental solution, with Perl's built in mechanism or one based on $ENV{ PWD } or qx( pwd ).

Aside: Combining an existing PERL5LIB for out-of-tree lookups with the "p5lib" option works well for most development situations. πŸ“

use lib qw( ../../../../Lib );

This works, but how many dots do you need to get all the working lib's into a module or #! code? Class distributed among several levels subdirectories may have qw( ../../../lib ) vs. qw( ../../../../lib ) or various combinations of them. Validating these by hand (let alone correcting them) leaves me crosseyed after only a short session. 😭

Anchor on a fixed lib directory.

Given a standard directory, it is possible to use something like:

BEGIN
{
    my ( $libdir ) = $0 =~ m{ ^( .+? )/SOMEDIR/ }x;

    eval "use lib qw( $libdir )";
}

This looks for a standard location (e.g., /path/to/Mylib) in the executable path (or cwd) and uses that.

The main problem here is that if the anchor ever changes (e.g., when moving code between projects or relocating directories now that SVN supports it) the path often has to change in multiple files. The regex also may have to support multiple platforms, or be broken into more complicated File::Spec code that probably looks pretty much like what

use FindBin::libs qw( base=Mylib )

does anyway.

FindBin::libs-1.2+ uses File::Spec 🧚

In order to accmodate a wider range of filesystems, the code has been re-written to use File::Spec for all directory and volume manglement. πŸ’œ


See Also πŸ‘€

  • File::Spec β€” This is used for portability in dis- and re-assembling directory paths based on $FindBin::Bin.
  • Older code. β€” FindBin::libs_5_8.pm is installed if $^V indicates that the running perl is prior to v5.10. See the ./versions dir in the distro for list of Perl version increments.

BUGS πŸ’€

  • In order to avoid including junk, FindBin::libs uses '-d' to test the items before including them on the library list.

abs_path causes too many issues where symlinks are useful, at this point I've given up trying to make it work. This may leave multiple paths to the same location in multiple points of the directory stack. So be it.

This also means I've had to replace FindBin as the source of the execution directory. I've used a mirror of the Raku code for FindBin and FindBin::Parent here as seprate modules. These depend only on File::Spec and do not use abs_path.

  • File::Spec 3.16 and prior have a bug in VMS of not returning an absolute paths in splitdir for dir's without a leading '.'. Fix for this is to unshift '', @dirpath if $dirpath[0]. While not a bug, this is obviously a somewhat kludgy workaround and should be removed (with an added test for a working version) once the File::Spec is fixed.
  • The hack for prior-to-5.12 versions of perl is messy, but is the only I've found that works for the moment on *NIX, VMS, and MSW. I am not sure whether any of these systems are normally configured to share perl modules between versions. If the moduels are not shared on multiple platforms then I can make this work by managing the installation rather than checking this every time at startup.

For the moment, at least, this seems to work.


AUTHOR ✍️

Steven Lembark, Workhorse Computing <lembark@wrkhors.com>

Copyright (C) 2003-2024, Steven Lembark, Workhorse Computing.

LICENSE πŸ“œ

This code is released under the same terms as Perl-5.40 or any later version of Perl.


And that's the whole page bestie, we made it!! πŸŽ‰ This lil masterpiece is FindBin::libs(3pm), perl v5.40.1, dated 2025-11-09 β€” go forth and use it responsibly πŸ’–βœ¨

πŸ“¦ where this page comes from