Search code examples
perldirectoryfilepathfile-exists

How do you get the first existing ancestor directory given a file path?


In Perl, if given a file path, how do you find the first existing ancestor?

For example:

  • If given the path /opt/var/DOES/NOT/EXIST/wtv/blarg.txt and directory /opt/var/DOES/ is not present but directory /opt/var/ is, the result should be /opt/var/.
  • If given the path /home/leguri/images/nsfw/lena-full.jpg and directory /home/leguri/images/nsfw/ does not exist, but directory /home/leguri/images/ does, the result should be /home/leguri/images/.

Is there a module or function which does this, or is it just a matter of splitting the path on / and testing for existence?


Solution

  • The closest I know of is Path::Class, which doesn't do exactly what you want but may save you a couple of steps in splitting the path.

    use Path::Class 'dir';
    
    sub get_existing_dir {
        my ( $path ) = @_;
    
        my $dir = dir( $path );
        while (!-d $dir) {
            $dir = $dir->parent;
        }
        return $dir->stringify;
    }
    
    my $file = '/opt/var/DOES/NOT/EXIST/wtv/blarg.txt';
    my $dir = get_existing_dir( $file );
    print $dir;