tags:

views:

61

answers:

2

Suppose I have:

my $a = "http://site.com";
my $part = "index.html";
my $full = join($a,$part);
print $full;
>> http://site.com/index.html

What do I have to use as join, in order to get my snippet to work?

EDIT: I'm looking for something more general. What if a ends with a slash, and part starts with one? I'm sure in some module, someone has this covered.

+7  A: 

I believe what you're looking for is URI::Split, e.g.:

use URI::Split qw(uri_join);
$uri = uri_join('http', 'site.com', 'index.html')
Ether
+2  A: 

No need for ‘join‘, just use string interpolation.

my $a = "http://site.com";
my $part = "index.html";
my $full = "$a/$part";
print $full;
>> http://site.com/index.html

Update:

Not everything requires a module. CPAN is wonderful, but restraint is needed.

The simple approach above works very well if you have clean inputs. If you need to handle unevenly formatted strings, you will need to normalize them somehow. Using a library in the URI namespace that meets your needs is probably the best course of action if you need to handle user input. If the variance is minor File::Spec or a little manual clean-up may be good enough for your needs.

my $a = 'http://site.com';
my @paths = qw( /foo/bar foo  //foo/bar );

# bad paths don't work:
print join "\n", "Bad URIs:", map "$a/$_", @paths;

my @cleaned = map s:^/+::, @paths;
print join "\n", "Cleaned URIs:", map "$a/$_", @paths;

When you have to handle bad stuff like $path = /./foo/.././foo/../foo/bar; is when you want definitely want to use a library. Of course, this could be sorted out using File::Spec's cannonical path function.

If you are worried about bad/bizarre stuff in the URI rather than just path issues (usernames, passwords, bizarre protocol specifiers) or URL encoding of strings, then using a URI library is really important, and is indisputably not overkill.

daotoad
Yeah, but what if $a ends with /, and $part starts with it?
Geo
If you have complex needs, use a complex library. If you have simple needs and sanitzed inputs, use a simple approach. Although handling a trailing or leading slash is not exactly complex. You will have more problems if you don't read the perldoc for join and try to use it improperly (your sample code doesn't do what you think it does-to concatenate your URI elements with `join`, you should be using `join'/', $a, $part;`). You can also use `File::Spec` to concatenate your paths. Scale your solution to your problem set and dependencies with care.
daotoad