Pergunta

Is there a Perl module (preferably core) that has a function that will tell me if a given filename is inside a directory (or a subdirectory of the directory, recursively)?

For example:

my $f = "/foo/bar/baz";

# prints 1
print is_inside_of($f, "/foo");

# prints 0
print is_inside_of($f, "/foo/asdf");

I could write my own, but there are some complicating factors such as symlinks, relative paths, whether it's OK to examine the filesystem or not, etc. I'd rather not reinvent the wheel.

Foi útil?

Solução

Path::Tiny is not in core, but it has no non-core dependencies, so is a very quick and easy installation.

use Path::Tiny qw(path);

path("/usr/bin")->subsumes("/usr/bin/perl");   # true

Now, it does this entirely by looking at the file paths (after canonicalizing them), so it may or may not be adequate depending on what sort of behaviour you're expecting in edge cases like symlinks. But for most purposes it should be sufficient. (If you want to take into account hard links, the only way is to search through the entire directory structure and compare inode numbers.)

Outras dicas

If you want the function to work for only a filename (without a path) and a path, you can use File::Find:

#!/usr/bin/perl
use warnings;
use strict;

use File::Find;

sub is_inside_of {
    my ($file, $path) = @_;
    my $found;
    find( sub { $found = 1 if $_ eq $file }, $path);
    return $found
}

If you don't want to check the filesystem, but only process the path, see File::Spec for some functions that can help you. If you want to process symlinks, though, you can't avoid touching the file system.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top