Thursday, August 4, 2011

Create a Unique list using perl

Consider the following example:


@a=('one','Two','Two','Four','Three','Four','Four','Five');
%seen = (); @uniqu = grep { ! $seen{$_} ++ } @a;
print "@uniqu";

Ouput:

G:\perl_programs>perl perl_grep.pl
one Two Four Three Five

Analysis:
In this case the grep returns $_ when the value is 1.Here since "!" option is used
it reverses the condition so it is 1 when the $seen{$_} value is 0 which happens when the
item comes the first time.

So it will be much more clearer when you use map in place of grep which returns the return value.


@a=('one','Two','Two','Four','Three','Four','Four','Five');
%seen = (); @uniqu = map{ ! $seen{$_} ++ } @a;
print "@uniqu";

Output:

G:\perl_programs>perl perl_grep.pl
1 1 1 1 1
G:\perl_programs>
SO as you may see 1 is returned only for unique values only when it comes first time.

No comments:

Post a Comment