[英]How do I find, count, and display unique elements of an array using Perl?
我是Perl的新手程序員,希望獲得一些幫助。 我有一個數組列表,我試圖將基於管道的每個元素分成兩個標量元素。 從這里開始,我只想摘錄顯示“ PJ RER Apts to Share”作為第一要素的行。 然后,我只想打印第二個元素一次,同時計數每次元素出現的時間。 我在下面編寫了這段代碼,但無法弄清楚我要去哪里。 我可能忽略的地方可能很小。 任何幫助將不勝感激。
## 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
這非常粗糙,但是我會使用Perl的超棒哈希數組來幫助完成此任務。 我會記錄整個記錄,並用它來索引哈希數組和該值的增量。
foreach (@array) {
$myHash{$_}++;
}
完成后,循環遍歷您的哈希數組,您將擁有從增量計數器開始計數的唯一和重復記錄。
就像我說的那樣,這很粗糙,我敢肯定這種方法存在很多問題。 你們所有的Perl眾神都開除了。
您可以在List :: MoreUtils中使用uniq
函數從列表中刪除重復的條目。 通過在標量上下文中評估列表,可以輕松找到列表或數組中元素的數量:
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
我使用以下腳本:
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
這是您要找的東西嗎?
累積哈希中每個城市的出現次數。 密鑰將是城市名稱,值將是計數。 然后對鍵排序並輸出它們及其對應的值:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.