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.

To find the no of lines in the file perl

To find the no of lines in a file a one line command in Perl is sufficient

perl -ne "$. -- if /$^/;END {print $.}" filename

will display the no of lines in the file excluding the blank lines .

Analysis:
"$."  means the current record of the file

"$. --  if /$^/   means the one count will be reduced when it comes across the blank line.

END {print $.} means to print the "$." once it is completed with the file.