How to check if one path exists under another path in the file system in Perl?

Viewed 103

I have two paths. I want to check if one of them exists under the other one in the file system. I would do something like:

if (index($path,$subpath) != -1 && $path ne $subpath) {
    print("$subpath is subpath of $path\n");
}

But treating the path as string result with some issues. For example if the $path or $subpath are links, it won't work.

What is a robust way to check if $subpath exists under the $path? In case it's a link, it should check if the link (source file and not the target) itself exists under that path.

For example:

Path (realpath to dir): /a/b/c
Subpath (realpath to dir): /a/b/c/d

In that case it the second one is under the file system of first one. Another example:

Path (realpath to dir): /a/b/c
Subpath: /p/x/y/z

Where /p/x/y/z is a link to /a/b/c/d/e/f for example. In that case it is not under the filesystem of the first path because the link is located in /p/x/y/z and not under /a/b/c/.... Hope it make sense.

1 Answers

Using the very handy Path::Tiny module:

use Path::Tiny;

...

my $path = path("/a/b/c");
my $subpath = path("/a/b/c/d");
if ($path->subsumes($subpath)) {
    # True if $path is a prefix of $subpath
    ...
}

You can use the realpath method to resolve symlinks, .., etc. first if desired in one (Or both) paths:

my $path = path("/a/b/c")->realpath;
my $subpath = path("/p/x/y/z");
Related