Thursday, August 4, 2011

Create a Unique list using perl

Consider the following example:

%seen = (); @uniqu = grep { ! $seen{$_} ++ } @a;
print "@uniqu";


one Two Four Three Five

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.

%seen = (); @uniqu = map{ ! $seen{$_} ++ } @a;
print "@uniqu";


1 1 1 1 1
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 .

"$."  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.