urljoin
function implemented using PerlI'm an old Perl hand, but in my day job I use Python. One of the things I've found sorely missing from the standard Perl libraries these days is an equivalent to Python's urljoin
from the urlparse
module. Here's what I came up with:
# This is designed to work with http/https protocol URLs # TODO: support protocol-agnostic URLs sub urljoin { my ($a, $b) = @_; my $result; if (!$a) { return $b; } if (!$b) { return $a; } # latter full url overrides prior if ($b =~ m/^http/) { return $b; } # find protocol my $a_protocol = $a =~ m/(https?)\:\/\//; $a =~ s/$a_protocol\:\/\///i; my ($domain, @path_elements) = split(/\//, $a); if ($b =~ m/^\//) { $result = $a_protocol . '://' . $domain . $b; return $result; } pop(@path_elements); push(@path_elements, $b); $result = $a_protocol . '://' . $domain; foreach (@path_elements) { $result .= '/' . $_; } return $result; }