How can I remove relative path components but leave symlinks alone in Perl?

Posted by jnylen on Stack Overflow See other posts from Stack Overflow or by jnylen
Published on 2010-04-27T01:17:17Z Indexed on 2010/04/27 18:53 UTC
Read the original article Hit count: 268

Filed under:
|
|
|

I need to get Perl to remove relative path components from a Linux path. I've found a couple of functions that almost do what I want, but:

File::Spec->rel2abs does too little. It does not resolve ".." into a directory properly.

Cwd::realpath does too much. It resolves all symbolic links in the path, which I do not want.

Perhaps the best way to illustrate how I want this function to behave is to post a bash log where FixPath is a hypothetical command that gives the desired output:

'/tmp/test'$ mkdir -p a/b/c1 a/b/c2
'/tmp/test'$ cd a
'/tmp/test/a'$ ln -s b link
'/tmp/test/a'$ ls
b  link
'/tmp/test/a'$ cd b
'/tmp/test/a/b'$ ls
c1  c2
'/tmp/test/a/b'$ FixPath . # rel2abs works here
===> /tmp/test/a/b
'/tmp/test/a/b'$ FixPath .. # realpath works here
===> /tmp/test/a
'/tmp/test/a/b'$ FixPath c1 # rel2abs works here
===> /tmp/test/a/b/c1
'/tmp/test/a/b'$ FixPath ../b # realpath works here
===> /tmp/test/a/b
'/tmp/test/a/b'$ FixPath ../link/c1 # neither one works here
===> /tmp/test/a/link/c1
'/tmp/test/a/b'$ FixPath missing # should work for nonexistent files
===> /tmp/test/a/b/missing

© Stack Overflow or respective owner

Related posts about perl

Related posts about paths