Search code examples
perlurlhrefradix

How can I find the full URL from a relative URL in Perl?


I'm new to perl but was wondering if anyone know of a script that was similar to the following PHP version which works great!

private function resolve_href ( $base, $href ) {
    if (!$href)
        return $base;
    $rel_parsed = parse_url($href);
    if (array_key_exists('scheme', $rel_parsed))
        return $href;
    $base_parsed = parse_url("$base ");
    if (!array_key_exists('path', $base_parsed))
        $base_parsed = parse_url("$base/ ");
    if ($href{0} === "/")
        $path = $href;
    else
        $path = dirname($base_parsed['path']) . "/$href";
    $path = preg_replace('~/\./~', '/', $path);
    $parts = array();
    foreach ( explode('/', preg_replace('~/+~', '/', $path)) as $part ) { 
        if ($part === "..")
            array_pop($parts);
        elseif ($part!="") 
            $parts[] = $part;
    }
    $dir =  ( ( array_key_exists('scheme', $base_parsed)) ? $base_parsed['scheme'] . '://' . $base_parsed['host'] : "" ) . "/" . implode("/", $parts);
    return str_replace( "\/", '', $dir );
}

Any help is much appreciated


Solution

  • See URI:

    #!/usr/bin/perl
    
    use strict; use warnings;
    use URI;
    
    my $u = URI->new_abs('../foobar', 'http://foo.com/bar/poo/');
    print $u->canonical;
    

    Output:

    http://foo.com/bar/foobar