my @b = grep EXPR, @a;
is equivalent to
my @b;
foreach (@a) {
if (EXPR) {
push @b, $_;
}
}
In this case:
my @uniqueIPs;
foreach (@uniqueIPs) {
if (!$counts{$_}++) {
push @ipAddresses, $_;
}
}
As for post-incrementing,
$x++
is equivalent to
my $orig_x = $x;
++$x;
$orig_x
In this case:
my @uniqueIPs;
foreach (@uniqueIPs) {
my $old_count = $counts{$_};
$counts{$_}++; # Add one to count.
if (!$old_count) { # If it's the first time we've seen it,
push @ipAddresses, $_; # save it
}
}
So,
my %counts;
my @uniqueIPs = grep !$counts{$_}++, @ipAddresses;
is short for
my @uniqueIPs;
foreach (@uniqueIPs) {
$counts{$_}++; # Add one to count.
if ($counts{$_} == 1) { # If it's the first time we've seen it,
push @ipAddresses, $_; # save it
}
}
It is dense, but it's tried and true. Just add a comment for the less learned readers.
# Remove duplicates IP addresses by counting
# the number of times each address occurs.
my %counts;
my @uniqueIPs = grep !$counts{$_}++, @ipAddresses;
Oh by the way, you could also write it as follows if it's less confusing:
# Remove duplicates IP addresses by counting
# the number of times each address occurs.
my %counts;
my @uniqueIPs = grep ++$counts{$_} == 1, @ipAddresses;
|