简体   繁体   English

perl:计算数组中的唯一元素

[英]perl: count unique elements in array

I have a simple array with names in it, and I want to be able to easily print out the number of times each name appears. 我有一个带有名字的简单数组,我希望能够轻松打印出每个名字出现的次数。

I have tried making a ton of for loops an diff statements to first make another array with unique values then, trying to count the values in the orinal array and store them in a 3rd array. 我已经尝试制作一大堆for循环的diff语句,然后先创建另一个具有唯一值的数组,然后尝试计算orinal数组中的值并将它们存储在第3个数组中。 This seemed overly complex, and i wanted to see if maybe there was a much simpler way to do this. 这似乎过于复杂,我想看看是否有更简单的方法来做到这一点。

Use a hash to count the number of times each name occurs: 使用哈希计算每个名称出现的次数:

use warnings;
use strict;
use Data::Dumper;
$Data::Dumper::Sortkeys=1;

my @names = qw(bob mike joe bob);
my %counts;
$counts{$_}++ for @names;
print Dumper(\%counts);

__END__

$VAR1 = {
          'bob' => 2,
          'joe' => 1,
          'mike' => 1
        };
my %counts;
++$counts{$_} for @names;
my @unique = keys(%counts);

can be shortened to 可以缩短为

my %counts;
my @unique = grep !$counts{$_}++, @names;

The former loses the order of the names, whereas the latter has the advantage of preserving the order. 前者失去了名称的顺序,而后者具有保留顺序的优点。 (It keeps the first of duplicates.) (它保留了重复的第一个。)

The latter is also an idiomatic way of getting unique members of a list. 后者也是获取列表中唯一成员的惯用方法。 Normally, the has of counts are just a side-effect, but in this, it's a desired product. 通常情况下,计数只是副作用,但在这方面,它是一种理想的产品。 :) :)

The easiest way to do this is to take advantage of hashes. 最简单的方法是利用哈希值。

my @names = qw/joe bob sue bob mike sally mike bob sally dale joe/;
my %counts;
$counts{$_}++ for @names;

This will give you a hash that looks like: 这将为您提供如下所示的哈希:

      'dale' => 1,
      'sue' => 1,
      'joe' => 2,
      'mike' => 2,
      'bob' => 3,
      'sally' => 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM