How to concatenate pathname and relative pathname?
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.
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";
$ 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
精彩评论