2015-04-23 56 views
0

假設我有幾個變量,$x, $y, $z, $a, $b, $c,我想確保它們都具有相同的值。在Perl中比較多個數值

我可以用類似if ($x == $y == $z == $a == $b == $c)的東西來測試,以避免多重二進制比較,即(if $x == $y and $x == $z and $y == $z ...)?

有沒有什麼辦法可以用一個簡短而簡單的測試來做所有的比較?

+1

我想是的。試一試! –

+0

如果您有4個或更多變量,則二進制比較過多。 :)))對我來說太多了,至少。 – Stefan

+0

試了一下。多重比較不起作用。有人知道任何詭計嗎? – Stefan

回答

7
if (grep $x != $_, $y, $z, $a, $b, $c) { 
    print "not all the same\n"; 
} 
+0

你只是打敗了我這個解決方案:) – mttrb

4

$x == $y and $x == $z and $y == $z相當於$x == $y and $x == $z由於平等是可傳遞的。後者也是最佳解決方案,N個變量的N-1比較。

如果你有一個數組,你可以使用uniqList::MoreUtils

use List::MoreUtils qw(uniq); 

my @arr1 = qw(foo foo foo foo foo foo); 
my @arr2 = qw(foo BAR foo foo foo foo); 

print "arr1: ", (uniq @arr1) == 1 ? "All same" : "Different" , "\n"; 
print "arr2: ", (uniq @arr2) == 1 ? "All same" : "Different" , "\n"; 

(如果您有多個變量更多,沒有一個數組,它可能是值得考慮重寫代碼。 ..)

3

您可以使用List::MoreUtils::first_index

#!/usr/bin/env perl 

use strict; 
use warnings; 

use List::MoreUtils qw(first_index); 

my ($x, $y, $z, $a, $b, $c) = (1) x 6; 

if (are_all_same($x, $y, $z, $a, $b, $c)) { 
    print "They all have the same value\n"; 
} 

$c = 3; 

unless (are_all_same($x, $y, $z, $a, $b, $c)) { 
    print "At least one has a different value than the others\n"; 
} 

sub are_all_same { 
    my $x = shift; 
    -1 == first_index { $x != $_ } @_; 
} 

當然,還有的在一個小範圍內有這麼多的變量是否合適(是否從Fortranitis痛苦?)問題,以及人們是否應該使用哈希來避免這樣的問題第一名。

您也可以使用are_all_same與一個大陣列,它會施加最小的額外的空間和時間的懲罰。

+0

哇,奇妙的答案和評論。感謝Sinan Unur,Amadan和ysth。他的答案簡潔明瞭,他得到了積分。 :) – Stefan

1

如果它們全都相同,那麼特別是第一個必須等​​於所有剩下的。所以建議使用List::Util::all

use List::Util 'all'; 

if(all { $x == $_ } $y, $z, $a, $b, $c) { 
    ... 
}