The
s{ ([^/]+) /[.]{2}/ \1 } /$1/gx; regex only handles the
'foo/../foo' case; it does not handle something like
'foo/bar/../../baz'.
Purely as a mental exercise, a deprecated regex approach to handling repeated return to a parental directory might be something like:
>perl -wMstrict -le
"my $parent = qr{ \.\. / }xms;
my $dir = qr{ (?> [^/]+ /) (?<! $parent) }xms;
print 'output:';
for my $f (@ARGV) {
1 while $f =~ s{ $dir $parent }{}xmsg;
print $f
}
"
/vobs/foo/../foo/bar/me/my/../../me/my/moo
/vobs/foo/../bar/me/my/../../ma/mo/moo
/vobs/x/y/z/../../../x/y/z/filename
/vobs/x/y/z/../../../a/b/c/filename
/a/../b/c/d/../../e/f/g/h/i/../../../j/k/l/m/n/o/p/../../../../q
output:
/vobs/foo/bar/me/my/moo
/vobs/bar/ma/mo/moo
/vobs/x/y/z/filename
/vobs/a/b/c/filename
/b/e/f/j/k/l/q
However, this falls into the class of Stupid Regex Tricks because:
- I doubt it covers all possible variations of *nix path;
- Even if it covers all such variations (or the subset thereof that the OPer is interested in), extensive testing would be needed to verify this;
- It does not handle symlinks (see Re^3: 2 substitution problems below);
- It is not portable to other file systems;
- And finally, I'm sure there are a few other objections one could think of given a little time.
As Amphiaraus said, the preferred solution would be some module like Cwd that would overcome all these objections.
Update: Added symlink objection to list of regex solution objections per parv.
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.