How can I find two parent directories in perl?

I have a path: /path/to/here/file.txt

.

I want to receive /path/to/

Using

 my ($file, $dir) = fileparse($fullPath);

      

I can get file.txt

and/path/to/here/

How do I get it only /path/to/

?

+3


source to share


2 answers


use Path::Class qw( file );

say file("/path/to/here/file.txt")->dir->parent;

      



Note that this does not perform any file system checks, so it returns /path/to

even if it /path/to

is a symbolic link and therefore is not really the parent directory.

+4


source


Using Path :: Tiny :

$ perl -MPath::Tiny -e 'CORE::say path($ARGV[0])->parent->parent' /path/to/here/file.txt

      



This does not perform a file system check. Doing this using only File :: Spec tends to get tedious. I'm not sure about the following works:

$ perl -MFile::Spec::Functions=splitpath,catpath,catdir,splitdir -e \
 '($v, $d) = splitpath($ARGV[0]); @d = splitdir $d; splice @d, -2;  \
 CORE::say catpath($v, catdir (@d))' /path/to/here/file.txt

      

+2


source







All Articles