2015-02-10 79 views
-1

我有一个数据集为了从数组中删除重复的元素在Perl

10-101570715-101609901-hsa-mir-3158-1 10-101600739-101609661-ENSG00000166171 10-101588288-101609668-ENSG00000166171 10-101588325-101609447-ENSG00000166171 10-101594702-101609439-ENSG00000166171 10-101570560-101596651-ENSG00000166171 

10-103389007-103396515-hsa-mir-1307 10-103389041-103396023-ENSG00000173915 10-103389050-103396074-ENSG00000173915 10-103389050-103396441-ENSG00000173915 10-103389050-103396466-ENSG00000173915 10-103389050-103396466-ENSG00000173915 

除了在每一行的第一个元素,我有多个值,这是多余的,我想删除冗余值。我写了一个代码,但我觉得它的工作不错。

open (fh, "file1"); 
while ($line=<fh>) 
{ 
chomp ($line); 
@array=$line; 
my @unique =(); 
my %Seen =(); 
foreach my $elem (@array) 
    { 
    next if $Seen{ $elem }++; 
    push @unique, $elem; 
    } 
print @unique; 
} 
+1

'使用严格的;使用警告;使用Data :: Dumper;打印Dumper \%看到;'你不是在寻找重复使用全行? – 2015-02-10 06:14:22

+0

不,使用实线不重复,只搜索元素,重复在一行 – 2015-02-10 06:22:56

回答

5

哈希是重复检测:

my %seen; 
my @removeduplicate = grep { !$seen{$_}++ } @array; 

对我来说,下面的代码工作正常:

use strict; 
use warnings; 

my %seen; 
open my $fh, "<", 'file.txt' or die "couldn't open : $!"; 
while (my $line = <$fh>) 
{ 
    chomp $line; 
    my @array = split (' ', $line); 
    my @removeduplicate = grep { !$seen{$_}++ } @array; 
    print "@removeduplicate\n"; 
} 
+0

冗余值仍然存在 – 2015-02-10 06:20:47

+1

@MANAUWERRAZA:看看我编辑的答案。总是使用'使用警告'和'使用严格'和三个参数来进行文件操作。 – serenesat 2015-02-10 06:43:59

+0

谢谢,之前编写的代码也工作过,这是我的疏忽大部分。 – 2015-02-10 07:24:28