Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Explain the code

by gopalr (Priest)
on Jul 24, 2008 at 12:54 UTC ( #699861=note: print w/replies, xml ) Need Help??


in reply to Explain the code

This approach is merges the construction of the %seen hash with the extraction of unique elements.

1. reading elements from @array

2. If the current element ($_) and it is not in the hash (%seen), it will push into @result. Then it stored into hash(%seen). As we know hash will not allow duplicate value

Thanks
Gopal

Replies are listed 'Best First'.
Re^2: Explain the code
by olus (Curate) on Jul 24, 2008 at 12:58 UTC

    %seen will also have the number of occurrences of every element of @a.

      How? If the array (@a) has duplicate values, hash will eliminate that.

        Noticed the ++ in !$seen{$_}++?

        perl -MData::Dumper -e '@a=(1, 2, 1, 2, 3); my @result = grep { !$seen +{$_}++ } @a; print Dumper(\%seen);' $VAR1 = { '1' => 2, '3' => 1, '2' => 2 };
        The ++ is evaluated for every item in @a, grep only checks its return value and picks (or not picks) the element based on that value.
        $seen{4} = 3 means that 4 has been seen 3 times.

        Unless I state otherwise, all my code runs with strict and warnings

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://699861]
help
Chatterbox?
[Discipulus]: see Re: from txt file to array erix
[erix]: yeah, I ask for the text (I don't see signatures)
[Discipulus]: dear brother karl has "Furthermore I consider that Donald Trump must be impeached as soon as possible" in his sig
[erix]: ah, thanks Discipulus
[1nickt]: erix perhaps you could kindly point out your technique to roho and everyone will be happy.
[Discipulus]: but i'm also animalist, so i' hirted by 1nickt's sig: The way forward always starts with a mammal test... grin..
[erix]: I might if I did remember. It's probably somewhere in the site docs
[uhClem]: I don't favor that sort of thing around here but the place for our politics is wherever we live.
[uhClem]: And besides, the objection to it was off-topic.

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (9)
As of 2017-06-22 12:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many monitors do you use while coding?















    Results (519 votes). Check out past polls.