2014-09-19 40 views
-3

鑑於元件的陣列中只出現一次的元素,如何發現只有在該陣列發生一次的元件:Perl的發現,在一個數組

my @array = qw(18 1 18 3 18 1 1 2 3 3); 

結果應該是:2

+4

請顯示您的工作 - SO不是代碼編寫服務。作爲10的入門者,我會提供:使用散列,因爲散列很適合查找唯一身份。而且 - 不要使用帶有逗號分隔值的'qw' - 這太髒了。 – Sobrique 2014-09-19 15:50:32

+0

不要混合使用逗號和qw(通常);你的數組將包含例如「3」, – ysth 2014-09-19 15:54:33

+1

...和「使用警告;'會警告'qw'錯誤。 – toolic 2014-09-19 15:56:11

回答

7

這是perlfaq5 - How can I remove duplicate elements from a list or array?

只需使用散列來計算元素,然後打印只顯示一次的元素。

use strict; 
use warnings; 

my @array = qw(18 1 18 3 18 1 1 2 3 3); 

my @nondup = do { 
    my %count; 
    $count{$_}++ for @array; 
    grep {$count{$_} == 1} keys %count; 
}; 

print "@nondup\n"; 

輸出:

2 
+0

僅用於踢球,單線:'my @nondup =地圖鍵%{$ _-> {unique} || {}},List :: Util :: reduce {$ a - > {seen} {$ b } ++?刪除$ a - > {unique} {$ b}:undef $ a - > {unique} {$ b}; $ a} {},@array;' – ysth 2014-09-19 16:28:57

+0

@ysth或者在荒謬性上略有變化:'my @nondup = map {my $ h = $ _; (grep {$ h - > {$ _} == 1} keys%$ h)} List :: Util :: reduce {$ a - > {$ b} ++; $ a} {},@array;' – Miller 2014-09-19 19:22:42

1

您還可以在簡單的方式嘗試。

use strict; 
use warnings; 
my @array = qw(7 8 7 5 18 1 18 3 18 1 1 2 3 3 4 5 6 7); 
my $tm = ""; 
my %hash=(); 
foreach $tm(@array){  
    if(exists $hash{$tm}){ 
     $hash{$tm} = ""; 
    } 
    else{ 
     $hash{$tm} = "$tm";  
    } 
} 
print join ("\n", values %hash);exit;