ramdat has asked for the wisdom of the Perl Monks concerning the following question:

Can anyone please explain me the following piece of code..Would be really grateful to u...Thanks in advance...

my @r = grep{++$uniq{ join $; , sort @$_ } == 1 } @AoA;;

Replies are listed 'Best First'.
Re: code explanation
by DrHyde (Prior) on Aug 04, 2011 at 10:39 UTC

    Read it from right to left.

    @AoA (which from its name we can assume is an array of arrayrefs) is the input to grep. grep filters it, and spits out a list that is the same size or smaller than @AoA and that list gets put into @r.

    The bit inside braces is how grep filters. Each value from @AoA in turn is assigned to $_ and then the contents of the braces are executed. If the result is true, the array element is spat back out, otherwise it isn't - it gets filtered out.

    join $;, sort @$_ first dereferences $_, which is assumed to be an array reference, giving a list. That list is sorted. It is then glued together to make a string, using $; as the separator. $; is an obsolete hangover from perl4, whose default value is an unprintable ASCII character, see perlvar for details.

    This string is then used as a key in the %uniq hash to look up a value or, if the key doesn't exist, create it. ++ is a pre-increment, meaning that the value we just got from the hash is incremented before being used. Finally the == compares that incremented value to 1.

    The overall result is that @r contains only the unique elements of @AoA, where two elements are defined to be the same if they have the same number of elements with the same values but in any order.

    The code is buggy, as it may fail if elements contain $;. It would be better to use something like Text::CSV_XS instead of the naïve join.

Re: code explanation
by cdarke (Prior) on Aug 04, 2011 at 10:39 UTC
    sort will sort the array reference by each element of @AoA
    join joins the result together using the contents of $;
    The resulting string is used as a key to %uniq, and the value is incremented
    If the value is one, then True is returned to grep, and a copy of the original value from @AoA is stored in @r.

    Try breaking down a statment like this into its parts, and try each part at a time to see what it does. Experimenting will teach you a lot.
Re: code explanation
by Utilitarian (Vicar) on Aug 04, 2011 at 10:49 UTC
    Why not see what it does and work it out...
    perl -MData::Dumper -e ' my @AoA=( ["one", "two", "three"], ["four", "five", "six"], ["four","five","six"], ["seven", "eight", "nine"], ["eight", "seven", "nine"]); my @r = grep{++$uniq{ join $; , sort @$_ } == 1 } @AoA; print "\@r is now:\n", Dumper(\@r), "\%uniq is now:\n",Dumper(\%uniq)'
    Then check out $; in perlvar.

    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."