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


i need perl remove relative path components linux path. i've found couple of functions want, but:

file::spec->rel2abs little. not resolve ".." directory properly.

cwd::realpath much. resolves symbolic links in path, not want.

perhaps best way illustrate how want function behave post bash log fixpath hypothetical command gives desired output:

'/tmp/test'$ mkdir -p a/b/c1 a/b/c2 '/tmp/test'$ cd '/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 1 works here ===> /tmp/test/a/link/c1 '/tmp/test/a/b'$ fixpath missing # should work nonexistent files ===> /tmp/test/a/b/missing 

alright, here came with:

sub mangle_path {   # not portable   # attempt remove relative components path - can return   # incorrect results paths ../some_symlink/.. etc.    $path = shift;   $path = getcwd . "/$path" if '/' ne substr $path, 0, 1;    @dirs = ();   for(split '/', $path) {     pop @dirs, next if $_ eq '..';     push @dirs, $_ unless $_ eq '.' or $_ eq '';   }   return '/' . join '/', @dirs; } 

i know possibly insecure , invalid, input routine come me on command line, , solves couple of tricky use cases me.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -