Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Get unique fields from file

by johngg (Canon)
on Jan 06, 2022 at 11:43 UTC ( #11140217=note: print w/replies, xml ) Need Help??


in reply to Get unique fields from file

I had this piece of code used somewhere but I hardly can understand it:

Breaking that down into stages:-

  • Create an empty hash %seen that will track occurrences of elements in @output

  • Pass each element of @output one at a time into the grep as $_ for filtering

  • The first time a particular value occurs in $_ the hash value $seen{ $_ } will be empty, hence "false" and ! seen{ $_ } i.e. "not false" is "true" so that the $_ value passes out of the grep into @uniqueOutput

  • Note also the ++ post-increment operator in ! $seen{ $_ }++ that increments the value of $seen{ $_ } after the test ! seen{ $_ } has been done, which means that after the first occurrence of a particular value the hash for it will no longer be blank, i.e. "false", but 1, 2 ... etc. depending on how many times it occurs, which evaluates to "true" and therefore "not true" is "false" so that second and subsequent occurrences will not pass from the grep into @uniqueOutput

My preference is to limit the scope of %seen to a do block so that it isn't left lying around.

johngg@abouriou:~/perl/Monks$ perl -Mstrict -Mwarnings -E ' say q{}; my @arr = qw{ a b c d c e f a b b g d }; my @uniq = do { my %seen; grep { not $seen{ $_ } ++ } @arr; }; say qq{@uniq};' a b c d e f g

I hope this makes the process clearer for you but ask further if something is still not clear.

Cheers,

JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11140217]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2022-08-10 08:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?