Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Uniq and sort in perl

by Utilitarian (Vicar)
on Jul 12, 2012 at 08:59 UTC ( #981335=note: print w/replies, xml ) Need Help??

in reply to Uniq and sort in perl

Any time you need to get a unique list in Perl you should think of using a hash. Say you defined a hash called %seen outside the while loop and changed the print line to read...
print "$vm, $filer, \n" if ! $seen{"$vm:$filler"}++;
This will print the entry the first time and increment the seen flag for that pair, now subsequent identical results will encounter a set flag and not print as a result

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

Replies are listed 'Best First'.
Re^2: Uniq and sort in perl
by slayedbylucifer (Scribe) on Jul 12, 2012 at 09:22 UTC

    Utilitarian, I can't thank you enough. Your solution is **exactly** what I was looking for. Thank you very Much !!

    But, unfortunately i am not able to decode or understand your oneliner. Could you guide me to some documentation for the same.

    Thanks Again for the lightning fast response.

      What is happening in that one liner:
      print "$vm, $filer, \n" if ! $seen{"$vm:$filler"}++

      It's quite an elegant piece of code, with a lot going on. So let's break it down:

      • The hash called '%seen' is being checked - to see if it contains a key called "$vm:$filler". The value of this is being tested for being 'false'. (because there's 'if !' which is 'if not') - which is literally 'if not seen'
      • So if $seen{"$vm:filler"} is _not_ 'true' - we haven't seen it, and so we print it.
      • And then that ++ kicks in, to post increment, 'adding one' to $seen{"$vm:$filler"}' - so the first time we try doing that, it's going to be undefined (and thus false) triggering a print. Second time, it'll be 'non zero' and so evaluate as 'true'.
      For bonus points, you can probably do:
      foreach my $key ( keys %seen ) { print "$key was seen $seen{$key} times\n"; }
      Does that make it any clearer?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://981335]
[Discipulus]: yes i saw your cell brother..
[Discipulus]: but now fuel is cheap and they still make some war.
[Discipulus]: capitalism is able to go to war by cycle, even.
[shmem]: some? are you jokin' ?
[shmem]: fuel is only one fuel that fuels the fools... it is all about power and control - which NOBODY will have.
[shmem]: ...can't have, since silly

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (10)
As of 2017-04-29 22:02 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (534 votes). Check out past polls.