2012-10-22 67 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