On Aug 15, 2006, at 2:28 PM, SFantar wrote:

Thank for your quick reply.
Your solution should suit me.
Can you give me more details/ explanations about your code?
What does your code do exactly?

Sure, we are using a hash table as a way to deal with duplicates, which is a standard idiom in Perl.

The idea is to use the elements you need to process as keys of a hash table. Hash tables held just one entry per key, so if you reassign to a key the entry in the hash table is overwritten, so to speak, not repeated. That's the way hash tables work, and we leverage that property.

For instance this is a way to count how many times each element of an array is repeated:

  my %counters = ();
  $counters{$_} += 1 for @array;

After that code the keys of %counters are the distinct elements of @array, and the hash associates the number of occurrences of each one in @array. Do you understand that example?

In the example I sent before, we used a similar trick but using grep, because we want to iterate over @array and filter duplicates out (you need to know grep to understand this):

  %seen = ();
  @uniq = grep {
      my $is_new = 0;
      if not exists $seen{$_} {
          $seen{$_} = 1;
          $is_new = 1;
      }
      $is_new;
  } @array;

That code is more explicit. We use a hash table called %seen to register seen strings. The way to accomplish that is that we assign an arbitrary value to $seen{john} the first time we encounter 'john', and so subsequent calls to exists $seen{john} will return true. In those cases $is_new remains 0 and grep filters that element out.

I wrote a condensed version of an analogous way to work that out.

-- fxn


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to