Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

relative paths

by John M. Dlugosz (Monsignor)
on Nov 26, 2001 at 10:13 UTC ( [id://127495]=perlquestion: print w/replies, xml ) Need Help??

John M. Dlugosz has asked for the wisdom of the Perl Monks concerning the following question:

Background: I'm still working on my documentation system. I'm storing the database of cross references as href targets that are all relative to the output tree. A reference within one document should be a relative path to get to the target.

The Problem: Given two paths that are expressed relative to the same starting point, express the first as a relative path from the second.

Example, given a\b\c to a\b\d, return ..\d .

I'm sure I can figure this out easily enough, so I'm not asking anyone to do it for me. But sharing code that's already been tested is another story! Since there is abs2rel and other goodies in File::Spec, I'm wondering if there is already a function that does this somewhere, so I don't have to write one.

Anybody seen it?

—John

Replies are listed 'Best First'.
Re: relative paths
by japhy (Canon) on Nov 26, 2001 at 10:33 UTC
    I tested this, and it seems to work:
    sub relpath { my ($from, $to) = @_; my @f = split '/', $from; my @t = split '/', $to; while (@f and @t) { shift(@f), shift(@t), next if $f[0] eq $t[0]; return join '/', ("..") x @f, @t; } return "./"; }

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: relative paths
by merlyn (Sage) on Nov 26, 2001 at 18:47 UTC
    Since there is abs2rel and other goodies in File::Spec
    abs2rel should be what you are using. Why is that function not suitable?

    -- Randal L. Schwartz, Perl hacker

      Because it never occured to me that it could hop between siblings (by inserting ..'s)—I thought it only trimmed off a root. I also don't know what it would do if given another relative path as the "current" parameter.

Re: relative paths
by clemburg (Curate) on Nov 27, 2001 at 00:16 UTC

    Been there. For me, the main problem was how to use abs2rel() - somehow I think the calling convention is backwards.

    Example:

    sub make_relative_path_to_website { my ($file) = @_; return File::Spec::Unix->abs2rel($config->{START_DIR}, File::Spec::Unix->rel2abs($file)) +; }

    Christian Lemburg
    Brainbench MVP for Perl
    http://www.brainbench.com

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://127495]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (9)
As of 2024-04-23 18:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found