How to concatenate pathname and relative pathname?

天大地大妈咪最大 提交于 2019-12-11 08:29:57

问题


I have a task where I need to concatenate 2 pathnames: absolute + relative in perl. The following describes what I am trying to achieve:

dir1/dir2/dir3/ + ../filename => dir1/dir2/filename
dir1/dir2/dir3/ + ../../filename => dir1/filename

I have only solution that counts ".." in relative path, say X, then splits the absolute path into dirs and count them - Y and finally concatenates only Y-X dirs with filename. This seems too bulky and I wonder whether better solution exists (I am sure it does). Thank you in advance.


回答1:


$ perl -MURI -E'say URI->new($ARGV[1])->abs($ARGV[0]);' \
    http://foo.com/dir1/dir2/dir3/ ../filename
http://foo.com/dir1/dir2/filename

$ perl -MURI -E'say URI->new($ARGV[1])->abs($ARGV[0]);' \
    http://foo.com/dir1/dir2/dir3/ ../../filename
http://foo.com/dir1/filename

It even works with two relative URLS like the ones you have.

$ perl -MURI -E'say URI->new($ARGV[1])->abs($ARGV[0]);' \
    /dir1/dir2/dir3/ ../filename
/dir1/dir2/filename

$ perl -MURI -E'say URI->new($ARGV[1])->abs($ARGV[0]);' \
    /dir1/dir2/dir3/ ../../filename
/dir1/filename



回答2:


You can look at File::Spec, namely catdir method:

use File::Spec;

print File::Spec->catdir('dir1/dir2/dir3', '../filename'),"\n";
print File::Spec->catdir('dir1/dir2/dir3', '../../filename', ),"\n";


来源:https://stackoverflow.com/questions/6579495/how-to-concatenate-pathname-and-relative-pathname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!