Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

rel2abs doesn't resolve relative paths?

by Cirollo (Friar)
on Jun 05, 2003 at 14:59 UTC ( #263360=perlquestion: print w/ replies, xml ) Need Help??
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?

Comment on rel2abs doesn't resolve relative paths?
Download Code
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? (use Cwd)
by grinder (Bishop) on Jun 05, 2003 at 16:01 UTC
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://263360]
Front-paged by tye
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2014-10-23 00:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (123 votes), past polls