I have seen one easy program. Well, the hole program i have understand except one thing and that is how Hash is working here :
Program ->Extracting Unique Elements from a List
@list = (20,30,40,60,40,20,30,2);
@uniq = ();
%seen = ();
foreach $item (@list) {
unless ($seen{$item})
{
# if we get here, we have not seen it before
push(@uniq, $item);
$seen{$item}++;
}
print %seen;
print"\n";
}
My question is how hash is comparing from its exiting value to current value i.e how it is checking weather that value is already there or not .If I m printing the %seen i am getting some value.how those values are coming ?
If it makes it clearer for your, change
to
The first time you encounter a particular item, it doesn’t exist as a key in the hash, so the
ifis entered. The body of theifcreates a key in the hash equal to the item.The second (and third and …) time you encounter a particular item, it exists as a key in the hash, so the
ifis not entered.By the way,
can be shortened to
And
can be shortened to
So the whole thing can be written as