in reply to Re^2: Counting unique instances from Array Sort: explanation needed
in thread Counting unique instances from Array Sort

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;

Replies are listed 'Best First'.
Re^4: Counting unique instances from Array Sort: explanation needed
by bradcathey (Prior) on Jan 07, 2008 at 19:09 UTC

    Brilliant. I think if I had all of Perl explained to me this way I'd be a saint in no time.

    Besides the overall deconstruction, rehearsing the pre/post incrementing has been helpful.

    Thanks NetWallah and ikegami!

    —Brad
    "The important work of moving the world forward does not wait to be done by perfect men." George Eliot

      Your welcome. In my case, it's "By explaining Perl this way, I became a saint in no time." :)