in reply to Counting unique instances from Array Sort

The essential idea here is that we are using a hash to keep track of the counts. A hash, as you well know, is a very efficient way to look-up a moderate number of values based on a “key” such as IP-address.

Now here's where the coder decided to take advantage of one of Perl's many “shortcuts.” He “knew” that if you increment ("++") a hash-key that doesn't exist yet, Perl will “helpfully” treat that key as though it did exist had the value zero.

As for me, I don't like to see code like that. The case where a particular key does not yet exist in a hash-structure is logically distinct from the case where it does. Therefore, I prefer to see that distinction expressly taken care of within the code, even if the resulting code is “inefficient.”

So I prefer to have something very pedantic, like:   (complete with comments!) ...

# Maintain a running count of all the unique IP-addresses seen ... foreach my $key (@address_list) { if (defined($ip_occurs[$key])) { $ip_occurs[$key]++; # seen again ... } else { $ip_occurs[$key] = 1; # first time ... } }

(The above code has been edited to fix an obvious dmub tpyo ...)

Notice that it does not matter in what order the keys are scanned when putting them into the hash-table. There is no reason to sort the keys in this loop. Instead, you will sort the keys when you extract them from the hash-table:

foreach my $key (sort keys %ip_occurs) { print "$key occurs $ip_occurs[$key] times\n"; }
(Caution: extemporaneous Perl! Not responsible for tpy0s...)