http://qs321.pair.com?node_id=263360

Cirollo has asked for the wisdom of the Perl Monks concerning the following question:

Consider running this from the directory /home/myuser:
use File::Spec::Functions qw/rel2abs/; print rel2abs("../bob/");' __END__ /home/myuser/../bob
Shouldn't rel2abs get rid of the '..' and print "/home/bob" instead of "/home/myuser/../bob"? If that's not the expected behavior, are there any standard functions that would return "/home/bob" or will I have to write my own subroutine to get rid of the ..'s?

Replies are listed 'Best First'.
Re: rel2abs doesn't resolve relative paths? (use Cwd)
by grinder (Bishop) on Jun 05, 2003 at 16:01 UTC
Re: rel2abs doesn't resolve relative paths?
by halley (Prior) on Jun 05, 2003 at 15:31 UTC

    The definition of "absolute" just means it starts with a slash. Some people refer to your intended result as a "canonical" path, and removing all backtracking as the "canonicalization" of a path. There are other elements to canonicalization, such as discovering aliased mount points or symlinks.

    Perhaps something like this will work for you.

    1 while ($path =~ s{ [^/]+ / \.\. / }{}x);

    --
    [ e d @ h a l l e y . c c ]

      And it is too bad that canonpath from File::Spec doesn't do even this (based on my testing on two systems, one Unix, one Win32).

                      - tye
Re: rel2abs doesn't resolve relative paths?
by Oberon (Monk) on Jun 07, 2003 at 01:17 UTC
    > ... are there any standard functions that would return "/home/bob" or will I have to write my own subroutine to get rid of the ..'s?

    My solution to this problem has been to grab File::VirtualPath. It's not standard, but at least you wouldn't have to write your own ...

    # warning! untested code ahead use File::VirtualPath; my $p = File::VirtualPath->new(); $p->path("/home/myuser"); # or use cwd() $p->chdir("../bob/"); print $p->path_string(); # should yield /home/bob

    And of course you could wrap all that up in a sub if you like. I like this particular solution because it works even if you're referring to a path that doesn't exist (maybe it doesn't exist yet, but it will, or it's a path to something other than a physical file in the file system).

    HTH.