与解析 HTML 一样,操作 URI 最好使用库来处理许多极端情况和格式复杂性。在这种情况下,使用非常常见的URI 库将 URI 分开并重新组合在一起。
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use URI;
sub path_to_query_string {
my $uri = shift;
my $file = shift;
# Turn it into a URI object if it isn't already.
$uri = URI->new($uri) unless eval { $uri->isa("URI"); };
# Get the path all split up.
my @path_pairs = $uri->path_segments;
# Strip everything up to what is the real filename.
my @path;
while(@path_pairs) {
push @path, shift @path_pairs;
last if $path[-1] eq $file;
}
# Put the path bits back.
$uri->path_segments(@path);
# Split each key/value pair
my @pairs;
for my $pair (@path_pairs) {
push @pairs, split /:/, $pair;
}
# Put them back on the URI
$uri->query_form(\@pairs);
return $uri;
}
my %test_urls = (
"http://intranet/myApp/index.cfm/go:welcome.home/fruit:orange/car:ford/age:37/music:rock" =>
"http://intranet/myApp/index.cfm?go=welcome.home&fruit=orange&car=ford&age=37&music=rock"
);
for my $have (keys %test_urls) {
my $want = $test_urls{$have};
is path_to_query_string($have, "index.cfm"), $want, "path_to_query_string($have)";
}
done_testing;