2017-08-04 46 views
3

我有一個路徑:/path/to/here/file.txt如何在perl中查找兩個父目錄?

我想/path/to/

使用

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

我能得到file.txt/path/to/here/

如何得到公正/path/to/

+0

你應該使用模塊,在下面的兩個答案,無論如何,由於多種原因。但只是順便說一句,你意識到你可以解析字符串(用正則表達式或分割),對吧? – zdim

回答

4
use Path::Class qw(file); 

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

注意,這不執行任何文件系統檢查,所以它會返回/path/to即使/path/to是一個符號鏈接,因而不是真正的父目錄。

2

使用Path::Tiny

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

這也不會執行任何文件系統檢查。只使用File::Spec往往會變得單調乏味。我不積極的以下工作:

$ 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