To answer your specifc example..
$file =~ s%/[^/]+/\.\.$%%
... will eat the last directory name that's up'ed by the trailing ..
To give a more general/complete example that can handle multiple .'s and ..'s at any point in the path.
# colapse /./ and /.$
1 while ($file =~ s%/\.(/|$)%$1%g);
# colapse /dir/../ and /dir/..$
# ignore /../../ and /../..$
1 while ($file =~ s%/[^/]+/(?<!/\.\./)\.\.(/|$)%$1%g);
# remove ^dir/../ and ^dir/../
# ignore ^../../ and ^../..
1 while ($file =~ s%^[^/]+/(?<!^\.\./)\.\.(/|$)%%);
# colapse ^/../ to /
1 while ($file =~ s%^/\.\./%/%);
# expand null to .
$file =~ s%^$%.%;
We need the itterations of each loop as each substitution may reveal additional matchs.
We need multiple expressions to get the order of susbistion right. That is /../../ should colapse the two proceding directoires and not itself.
I'm sure it can be reduced more than that but it is as simple as I can see it can be and still catch all the special cases.
I use something very similar to this at the beginning of my scripts to get the conical path for $0 and not the called path. Although spliting the path into its components and working backwards is probably easier/clearer than using a regex.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.