Friday, March 25, 2011

How to Count Duplicate Elements in a Perl Array

use strict;
use warnings;

# 1. Initialize an array using the qw() operator. 
# qw() stands for "quote words" and automatically creates a list of strings separated by spaces.
my @array = qw(foo bar foo bar baz foo baz bar foo);

# 2. Create an empty hash to store the count of each element.
# Hashes store data in key-value pairs. Here, the 'key' will be the word, and the 'value' will be its count.
my %counts = ();

# 3. Loop through every element in the array.
for (@array) {
    # In a 'for' loop without a named variable, Perl temporarily stores the current item in the special variable $_
    # This line looks up the current word in the hash and increments its value by 1.
    # If the word isn't in the hash yet, Perl automatically creates it with a starting value of 0, then adds 1.
    $counts{$_}++;
}

# 4. Iterate over the sorted keys of our populated hash.
# 'keys %counts' returns a list of all the unique words we found.
foreach my $key (keys %counts) {
    # Print the word (the key) and how many times it appeared (the value)
    print "$key = $counts{$key}\n";
}

No comments: