1lib::relative(3) User Contributed Perl Documentation lib::relative(3)
2
3
4
6 lib::relative - Add paths relative to the current file to @INC
7
9 # Path is relative to this file, not current working directory
10 use lib::relative 'path/to/lib';
11 use lib::relative '../../lib';
12
13 # Add two lib paths, as in lib.pm
14 use lib::relative 'foo', 'bar';
15
16 # Absolute paths are passed through unchanged
17 use lib::relative 'foo/baz', '/path/to/lib';
18
19 # Equivalent code using core modules
20 use Cwd ();
21 use File::Basename ();
22 use File::Spec ();
23 use lib File::Spec->catdir(File::Basename::dirname(Cwd::abs_path __FILE__), 'path/to/lib');
24
26 Adding a path to @INC to load modules from a local directory may seem
27 simple, but has a few common pitfalls to be aware of. Directly adding a
28 relative path to @INC means that any later code that changes the
29 current working directory will change where modules are loaded from.
30 This applies to the "." path that used to be in @INC by default until
31 perl 5.26.0, or a relative path added in code like "use lib
32 'path/to/lib'", and may be a vulnerability if such a location is not
33 supposed to be writable. Additionally, the commonly used FindBin module
34 relies on interpreter state and the path to the original script invoked
35 by the perl interpreter, sometimes requiring workarounds in uncommon
36 cases like generated or embedded code. This module proposes a more
37 straightforward method: take a path relative to the current file,
38 absolutize it, and add it to @INC.
39
40 If this module is already available to be loaded, it can be used as
41 with lib.pm, passing relative paths, which will be absolutized relative
42 to the current file then passed on to lib. Multiple arguments will be
43 separately absolutized, and absolute paths will be passed on unchanged.
44
45 For cases where this module cannot be loaded beforehand, the last
46 section of the "SYNOPSIS" can be copy-pasted into a file to perform the
47 same task.
48
50 Due to "__FILE__" possibly being a path relative to the current working
51 directory, be sure to use "lib::relative" or the equivalent code from
52 "SYNOPSIS" as early as possible in the file. If a "chdir" occurs before
53 this code, it will add the incorrect directory path.
54
55 All file paths are expected to be in a format appropriate to the
56 current operating system, e.g. "..\\foo\\bar" on Windows. "catdir" in
57 File::Spec can be used to form directory paths portably.
58
60 Report any issues on the public bugtracker.
61
63 Dan Book <dbook@cpan.org>
64
66 This software is Copyright (c) 2017 by Dan Book.
67
68 This is free software, licensed under:
69
70 The Artistic License 2.0 (GPL Compatible)
71
73 lib, FindBin, Dir::Self
74
75
76
77perl v5.34.0 2021-07-23 lib::relative(3)