user28104
user28104

Reputation: 39

Unique element in file - perl

I want to get the unique elements (lines) from a file which I will further send through email. I have tried 2 methods but both are not working:

1st way:

my @array = "/tmp/myfile.$device";
my %seen = ();
my $file = grep { ! $seen{ $_ }++ } @array;

2nd way :

my $filename = "/tmp/myfile.$device";
cat $filename |sort | uniq > $file

How can I do it?

Upvotes: 0

Views: 1003

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753665

If you rig the argument list, you can make Perl open the file automatically, using:

perl -n -e 'BEGIN{@ARGV=("/tmp/myfile.device");} print if $count{$_}++ == 0;'

Upvotes: 0

Vorsprung
Vorsprung

Reputation: 34317

You need to open the file and read it.

"cat" is a shell command not perl

Try something like this

my $F;
die $! if(!open($F,"/tmp/myfile.$device"));
my @array = <$F>;
my %seen = (); my $file = grep { ! $seen{ $_ }++ } @array;

The die $! will stop the program with an error if the file doesn't open correctly; @array=<$F> reads all the data from the file $F opened above into the array.

Upvotes: 1

ikegami
ikegami

Reputation: 385657

You seem to have forgotten to read the file!

open(my $fh, '<', $file_name)
   or die("Can't open \"$file_name\": $!\n");

my %seen;
my @unique = grep !$seen{$_}++, <$fh>;

Upvotes: 4

Related Questions