TMTOWTDI:
$_ = my $original = "/one/two///three/four/..//fourX/five////six/seven +"; # you can do job 1 alone like this: tr!/!/!s; print "1: $original -> $_\n"; # OR you can do jobs 1 and 2 together like this; my @srcpaths = split m!/+!, $original; my @outpaths = (); for my $p ( @srcpaths ) { if ( $p eq '..' ) { pop @outpaths; } else { push @outpaths, $p; } } $_ = join( "/", @outpaths ); print "2: $original -> $_\n";
The latter is more verbose, but it's easier to see and understand what's being done; also, it will work on things like /one/two/three/../../two/three (which the regex solutions suggested above don't handle). If you want, you can even test for existence as you go (with -d join("/",@outpaths) (*)), and test for paths that are just wrong (too many "/.."):
pop @outpaths or die "Bad path: $original\n";

The regex solutions were assuming you only want to remove the "/.." in cases where the next part of the path matched the previous part of the path, but it seems to me that you really should have a solution that handles all the "/.." cases -- it's entirely possible that you'll run into a lot of different ones.

(*) Update: footnote about -d join("/",@outpaths) -- with an absolute path like "/one/two", $p is an empty string on the first iteration, and you don't want to use "-d" on that. Putting full error checks into the loop would be something like this:

my @outpath = (); for my $p ( split m!/+!, $original ) { if ( $p eq '..' ) { pop @outpath or die "Bad path: $original"; } else { if ( @outpath ) { my $chk = join "/", @outpath, $p; die "Path not found: $chk" unless ( -d $chk ); } push @outpath, $p; } } my $goodpath = join "/", @outpath;

In reply to Re: 2 sed problems by graff
in thread Yet another substitution problem by Amphiaraus

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.