Perl/Array Sorting : Can someone please explain below code $h{$_}++

sub uniq {
    my %h;
    return grep { !$h{$_}++ } @_
}

The above code is to remove duplicates from array.

I am having hard time understanding below things (basically around highlighted code in bold)-

when was the value inserted in hash?
and are we only adding a key in Hash not values?

$h{$_}++

what "++" means here

Basically

$h{$_}++

returns the value of $h{$_} then increments it. If there is no value at $h{$_} perl will initialise it to zero.

So, for each value that $_ may be, the first evaluation is zero and subsequent evaluations are non-zero. The exclamation point negates the values into True if zero, False if non-zero.

Does that help?

Andrew

2 Likes