URIモジュールのメモ

各種メソッドの挙動。

use URI;
use Data::Dumper;

sub p {
    local $Data::Dumper::Indent = 1;
    print $_[0];
    print Dumper($_[1]);
}

my $url = 'http://example.com/foo/bar/00000.html?uid=aaaa&hoge=あああ';
my $uri   = URI->new($url);

p 'scheme       :',$uri->scheme;
p 'opaque       :',$uri->opaque;
p 'path         :',$uri->path;
p 'fragment     :',$uri->fragment ;
p 'as_string    :',$uri->as_string;
p 'canonical    :',$uri->canonical;
p 'authority    :',$uri->authority ;
p 'path_query   :',$uri->path_query;
p 'path_segments:',$uri->path_segments;
p 'query        :',$uri->query ;
p 'query_form   :',{ $uri->query_form };
$uri->query_form({ hoge => '88' });
p 'query        :',$uri->query ;
p 'query_form   :',{ $uri->query_form };
p 'userinfo     :',$uri->userinfo;
p 'host         :',$uri->host;
p 'port         :',$uri->port;
p 'host_port    :',$uri->host_port;
p 'default_port :',$uri->default_port;

__END__

実行結果

scheme       :$VAR1 = 'http';
opaque       :$VAR1 = '//example.com/foo/bar/00000.html?uid=aaaa&hoge=%82%A0%82%A0%82%A0';
path         :$VAR1 = '/foo/bar/00000.html';
fragment     :$VAR1 = undef;
as_string    :$VAR1 = 'http://example.com/foo/bar/00000.html?uid=aaaa&hoge=%82%A0%82%A0%82%A0';
canonical    :$VAR1 = bless( do{\(my $o = 'http://example.com/foo/bar/00000.html?uid=aaaa&hoge=%82%A0%82%A0%82%A0')}, 'URI::http' );
authority    :$VAR1 = 'example.com';
path_query   :$VAR1 = '/foo/bar/00000.html?uid=aaaa&hoge=%82%A0%82%A0%82%A0';
path_segments:$VAR1 = '';
query        :$VAR1 = 'uid=aaaa&hoge=%82%A0%82%A0%82%A0';
query_form   :$VAR1 = {
  'uid' => 'aaaa',
  'hoge' => 'あああ'
};
query        :$VAR1 = 'hoge=%82W%82W';
query_form   :$VAR1 = {
  'hoge' => '88'
};
userinfo     :$VAR1 = undef;
host         :$VAR1 = 'example.com';
port         :$VAR1 = 80;
host_port    :$VAR1 = 'example.com:80';
default_port :$VAR1 = 80;

んー、クエリ以外のURL部分のみを抽出ってできないのかな?メソッド組み合わせて自分でやれってこと?

print $uri->scheme.'://'.$uri->host.$uri->path;

__END__

実行結果

http://example.com/foo/bar/00000.html

それかクエリ削除してas_string?

my $clone = $uri->clone; # 元のuriを壊さない為
$clone->query_form({});
print $clone->as_string;

__END__

実行結果

http://example.com/foo/bar/00000.html

んー、なんかもっとスマートな解法がある気がする。