问题
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