in reply to Re: 2 substitution problems
in thread Yet another substitution problem

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:

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.

Replies are listed 'Best First'.
Re^3: 2 substitution problems
by parv (Parson) on Mar 28, 2009 at 16:24 UTC

    Given a path actually exists, problem with a solution not actually changing directories is specified in File::Spec/METHODS ...

    canonpath

    No physical check on the filesystem, but a logical cleanup of a path.

    $cpath = File::Spec->canonpath( $path ) ;

    Note that this does *not* collapse x/../y sections into y. This is by design. If /foo on your system is a symlink to /bar/baz, then /foo/../quux is actually /bar/quux, not /quux as a naive ../-removal would give you. If you want to do this kind of processing, you probably want "Cwd"'s "realpath()" function to actually traverse the filesystem cleaning up paths like this.

    Otherwise, OP should test|improve on AnomalousMonk's and/or graff's solutions.

      Otherwise, OP should test|improve on AnomalousMonk's and/or graff's solutions.
      Actually, the OP should not use those solutions at all – unless it's the solution to use the appropriate function in the Cwd or equivalent module.
        I think you missed "Otherwise", by which I meant to improve on two other solutions when a path does not actually exist on a file system (in case of configuration(s) to be passed around, for example).