2012-10-22 68 views
0

我需要两个URL在Perl比较。比较两个网址

网址由DOMAIN的唯一或DOMAIN /(用斜线终了根URL)是等效的。

这就是说,以下字符串应该等于数: “http://example.com”和“http://example.com/”。

+0

修剪斜杠并比较? –

+2

@MichalKlouda - 通过'http:// example.com /富/'和'HTTP:// example.com/foo'是不等价的 – Quentin

+0

可能只是检查,看看是否索引(A,B)+指数(B,A )!= -2 – jozefg

回答

5

comparsion

To compare two URLs, use the eq() method:  
if ($url_one->eq(url_two)) { ... } 

For example: 

use URI; 
my $url_one = URI->new('http://www.example.com'); 
my $url_two = URI->new('http://www.example.com/'); 

if ($url_one->eq($url_two)) { 
    print "The two URLs are equal.\n"; 
} 
The two URLs are equal. 
+0

您应该删除'$ url_one->路径(“/”);'因为这明确地将第一个路径是不是表明他们是相同的,如果你只是设定为等于第二个路径,包含前两行的URI。 – Quentin

+0

@Quentin做...谢谢这只是一个例子 – Ghostman

0

你可以这样做:

my $url_1 = 'http://www.example.com'; 
my $url_2 = 'http://www.example.com/'; 

if ($url_1 =~ m/\A$url_2\/\z/ || $url_2 =~ m/\A$url_1\/\z/) { 
    print "URLs are the same\n"; 
} 

嗯因为他们是真正有效的URL。 正则表达式只检查如果你在最后加上“/”,它仍然是相同的URL

所以如果你在$ url_1的末尾添加“/”,它会是'http:// www。 example.com/“,这将使第二个条件成为真实。

+0

错误:这会考虑平等​​http://www.example.com/foo和http://www.example.com/foo/ – porton

+0

我不明白它,你只是在那里给了2个平等的链接。 –

+0

他们不平等。无论出于何种原因,仅当URL仅由域组成时,添加斜杠才会更改URL。 foo和foo /不相等。 – porton