LoginSignup
3
3

More than 5 years have passed since last update.

Perl で相対 URL から絶対 URL を作成する

Last updated at Posted at 2015-11-08

URI モジュールの abs を使うのが一番簡単そうだった。

http://perldoc.jp/docs/modules/URI-1.35/URI.pod#COMMON32METHODS

絶対 URI リファレンスを返します。 もし $uri がすでに絶対であれば、それへのリファレンスが単に返されます。 $uri が相対であれば、$uri$base_uri をつなげることにより新しい 絶対 URI が組み立てられ、返されます。

use strict;
use warnings;
use utf8;

use URI;

print URI->new("index.html")->abs("http://example.com") ,"\n";
#=> http://example.com/index.html

print URI->new("/path/to/index.html")->abs("http://example.com") ,"\n";
#=> http://example.com/path/to/index.html

print URI->new("index.html")->abs("http://example.com/path/to/") ,"\n";
#=> http://example.com/path/to/index.html

print URI->new("index.html")->abs("http://example.com/path/to/example.jpg") ,"\n";
#=> http://example.com/path/to/index.html

print URI->new("http://www.example.com/foo/bar/index.html")->abs("http://example.com/path/to/example.jpg") ,"\n";
#=> http://www.example.com/foo/bar/index.html

print URI->new("index.html")->abs("http://example.com/path/to") ,"\n";
#=> http://example.com/path/index.html

print URI->new("../index.html")->abs("http://example.com/path/to/") ,"\n";
#=> http://example.com/path/index.html

new_abs というショートカットもある。

use strict;
use warnings;
use utf8;

use URI;

print URI->new_abs("index.html", "http://example.com") ,"\n";
#=> http://example.com/index.html

print URI->new_abs("/path/to/index.html", "http://example.com") ,"\n";
#=> http://example.com/path/to/index.html

print URI->new_abs("index.html", "http://example.com/path/to/") ,"\n";
#=> http://example.com/path/to/index.html

print URI->new_abs("index.html", "http://example.com/path/to/example.jpg") ,"\n";
#=> http://example.com/path/to/index.html

print URI->new_abs("http://www.example.com/foo/bar/index.html", "http://example.com/path/to/example.jpg") ,"\n";
#=> http://www.example.com/foo/bar/index.html

print URI->new_abs("index.html", "http://example.com/path/to") ,"\n";
#=> http://example.com/path/index.html

print URI->new_abs("../index.html", "http://example.com/path/to/") ,"\n";
#=> http://example.com/path/index.html

参考

How do I create an absolute URL from two components, in Perl? - Stack Overflow
http://stackoverflow.com/questions/1813678/how-do-i-create-an-absolute-url-from-two-components-in-perl

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3