Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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


In reply to Re: Get unique fields from file by johngg
in thread Get unique fields from file by sroux

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (2)
As of 2024-04-20 03:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found