2010-05-12 93 views
0

我是新手Perl程序員,並希望一些幫助。我有一個數組列表,我試圖將基於管道的每個元素分成兩個標量元素。從那裏,我想只突出讀作'PJ RER Apts to Share'的線條作爲第一個元素。然後,我想在每次出現元素時計算一次第二個元素。我在下面寫了一段代碼,但無法弄清楚我錯在哪裏。這可能是我只是俯視的小事。任何幫助將不勝感激。如何使用Perl查找,計算和顯示數組的獨特元素?

## CODE ## 

my @data = ('PJ RER Apts to Share|PROVIDENCE', 
     'PJ RER Apts to Share|JOHNSTON', 
     'PJ RER Apts to Share|JOHNSTON', 
     'PJ RER Apts to Share|JOHNSTON', 
     'PJ RER Condo|WEST WARWICK', 
     'PJ RER Condo|WARWICK'); 

foreach my $line (@data) { 
    $count = @data; 
    chomp($line); 
    @fields = split(/\|/,$line); 
    if (($fields[0] =~ /PJ RER Apts to Share/g)){ 
     @array2 = $fields[1]; 
     my %seen; 
     my @uniq = grep { ! $seen{$_}++ } @array2; 
     my $count2 = scalar(@uniq); 
     print "$array2[0] ($count2)","\n" 
    } 
} 
print "$count","\n"; 

## OUTPUT ## 

PROVIDENCE (1) 
JOHNSTON (1) 
JOHNSTON (1) 
JOHNSTON (1) 
6 

回答

2

我用下面的腳本:

my %elements = (); 

foreach (@data) { 
    chomp; 
    my ($f0, $f1) = split(/\|/); 
    $elements{ $f0 }{ $f1 }++; 
} 

while (my ($k, $v) = each(%elements)) 
{ 
    print "Key [$k] :\n"; 
    while (my ($field2, $count) = each(%$v)) 
    { 
     print " Field [$field2] appeared $count times\n"; 
    } 
} 

而且也產生:

Key [PJ RER Condo] : 
    Field [WARWICK] appeared 1 times 
    Field [WEST WARWICK] appeared 1 times 
Key [PJ RER Apts to Share] : 
    Field [JOHNSTON] appeared 3 times 
    Field [PROVIDENCE] appeared 1 times 

難道這就是你要找的人?

+0

這是排序字段還是以隨機順序回傳數據? – Luke 2010-05-13 16:28:16

+0

如果你想要進行排序,然後說'每個(排序%$ V)'在過去'while'循環。希望能幫助到你! – Phil 2010-05-13 23:26:50

3

這是非常粗略的,但我會使用Perl的真棒哈希數組來幫助完成此任務。我會記錄整個記錄並使用它來索引散列數組和值的增量。

foreach (@array) { 
    $myHash{$_}++; 
} 

當它這樣做,循環使用您的哈希數組,你就會有獨特的和重複的增量計數器計數的一致好評記錄。

就像我說的,這是非常粗糙的,我敢肯定有與方法的許多問題。你們所有的Perl神都會開火。

+7

這根本不是粗俗的,它是正確和習慣的方法。 – friedo 2010-05-12 15:41:15

3

可以使用uniq功能List::MoreUtils從列表中刪除重複項。以列表或數組元素的數量可以通過在標量上下文評估所述列表中容易地找到:

use strict; use warnings; 
use List::MoreUtils 'uniq'; 
my @list = qw(1 1 2 3 5 8); 

my @uniq = uniq @list; 
print 'list with dupes removed: ', join(', ', @uniq), "\n"; 
print 'number of elements in this list: ', scalar(@uniq), "\n"; 
 
list with dupes removed: 1, 2, 3, 5, 8 
number of elements in this list: 5 
0

積聚在散列每個城市的發生次數。關鍵將是城市名稱,價值將成爲伯爵。然後密鑰並將其輸出及其相應的值進行排序:

my @data = ('PJ RER Apts to Share|PROVIDENCE', 
    'PJ RER Apts to Share|JOHNSTON', 
    'PJ RER Apts to Share|JOHNSTON', 
    'PJ RER Apts to Share|JOHNSTON', 
    'PJ RER Condo|WEST WARWICK', 
    'PJ RER Condo|WARWICK'); 

foreach my $line (@data) { 
    chomp($line); 
    @fields = split(/\|/,$line); 
    if ($fields[0] eq "PJ RER Apts to Share"){ 
     $city = "\u\L$fields[1]"; 
     $apts{$city}++; 

    } 
} 

@city_sort = sort (@city); 
print map {"$_ $apts{$_}\n";} sort(keys %apts); 
$count = @data; 
print "$count","\n"; 

另外,你希望所有商家信息的次數或只是那些要匹配。如果是後面更改最後一行到:

$count = keys %apts;