I want to resolve a path like '/this/that/../instead/here/' to '/this/instead/here'.

Cwd::abs_path() will do it. It will also resolve symlinks. Which I foresee a possible problem with in the future, for what I am working on.

What I think I need is some way to resolve a path without resolving symlinks.. I looked at File::Spec::Functions 'canonpath', it cleans things up a bit- but that's all.

I was playing with the following script, but I don't trust my imperfect mind's ability to do this right..

use Test::Simple 'no_plan'; use strict; #use File::Spec::Functions; use constant DEBUG => 1; my $p = { # mess is => should be '/self/xplanatori' => '/self/xplanatori', '/usr/lib/perl5/../../' => '/usr', '/home/fake4/../fake/' => '/home/fake', '/resolve/me/../right/' => '/resolve/right', '/./resolve////me/../right/.' => '/resolve/right', '/../.././usr/././.' => '/usr', '/../.././////././.' => '/', '/.....' => '/.....', './//../' =>'/' }; #map { ok( canonpath($_) eq $p->{$_}, "$_" ) } keys %$p; map { ok( abs_path2($_) eq $p->{$_}, "[$_]" ) } keys %$p; sub abs_path2 { my $path = shift; print STDERR " [$path]\n" if DEBUG; $path=~s/(?<=\/)\.(?=\/|\z)/\//sg; # /./ or /. to / print STDERR " [$path]\n" if DEBUG; 1 while $path=~s/[^\/]+\/+\.\.[\/|\Z]*//g; # anything/../ to / print STDERR " [$path]\n" if DEBUG; $path=~s/\/{2,}/\//g; # /// to / $path=~s/(?<=.)\/+$//g; # a/ to a print STDERR " [$path]\n" if DEBUG; return $path; }

Any suggestions?


In reply to cleaning up absolute path without resolving symlinks by leocharre

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.