in reply to Unique Array Items

I'm suffering from idiom-dazzle! This works:

use strict; my @toBeMoved = qw(133 22 103 133 133 22 1 999); my %h; $h{$_} = 1 for @toBeMoved; @toBeMoved = sort {$a <=> $b} keys %h; print "@toBeMoved\n";

But what's up with the increment and equality test inside of the grep? I'm reading this as each grep pass will set the value of the current hash element to 1 by the increment operator, but what's going on w/ the equality test? Would a kindly monk please break this grep block down for me?

Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"

Replies are listed 'Best First'.
Re: Re: Unique Array Items
by thelenm (Vicar) on Nov 06, 2003 at 21:59 UTC

    In this code:

    my %h; my @toBeMoved = sort {$a <=> $b} grep {++$h{$_} == 1} @toBeMoved;

    the value associated with each element is incremented (not set to 1, that's important). So the grep block will only return a true value the first time a value is seen. E.g., the first time 133 is seen, ++$h{133} == 1 will be true. The second time 133 is seen, the block will return a false value, since $h{133} will now be 2, not 1. The block will only return a true value once for each unique value. Does that clear things up at all?

    -- Mike

    --
    XML::Simpler does not require XML::Parser or a SAX parser. It does require File::Slurp.
    -- grantm, perldoc XML::Simpler

      That does clear it up! Thank you very much thelenm! :)

      Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"