I am attempting to translate a possibly relative path to an absolute path. I need to correctly collapse . and .. if it appears in the path I am given.

I have toyed with this an awful lot today and I arrived at something like:

# NOTE: I have already prepended pwd if needed #remove . while( $path =~ m#/\./# ) { $path =~ s#/\.#/#; } # remove .. while( $path =~ m#/[^/]+?/\.\./# ) { $path =~ s#/[^/]+?/\.\.#/#; }
This was not satisfying - the m## and then an s### with exactly the same arguments was lacking. Remembering that s### returns true if something was replaced, I was able to reduce this to
#remove . while ( $path =~ s#/\./#/# ) {;} #remove .. while ( $path =~ s#/[^/]+?/\.\./#/# ) {;}
But this still does not please me. Using two loops when I feel I should only have to use one. Working a bit harder and unleashing the marvelous /e modifier, I was able to finally say
while ( $path =~ s#(/[^/]+)?/\.(\.)?/defined($2) ? "/" : "$1/"/e ) {;}
I am pleased but wonder what other ways the honored Monks have found to do this - my solution is likely to be a real CPU pig.

For reasons I cannot elucidate, this solution is right out

unless ( chdir $path ) { die "Couldn't there ($path) from here\n"; } return `pwd`;
To further the discussion, I will point out that using the /g modifier does not work - the regex engine does double quotish expansion only once and will not reapply the regex to the new string. A wise move, considering the evil deep recursions that could result.

Mik
Mik Firestone (perlus bigotous maximus )


In reply to Normalized directory paths by mikfire

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.