pmod
pmod

Reputation: 11007

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.

Upvotes: 2

Views: 2510

Answers (2)

ikegami
ikegami

Reputation: 386706

$ 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

Upvotes: 1

bvr
bvr

Reputation: 9697

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";

Upvotes: 4

Related Questions