显示重复记录

时间:2012-04-19 15:10:51

标签: perl

我有一个如下代码来解析文本文件。在文本文件的所有行上显示“Enter:”关键字后面的所有单词。我在“Enter:”关键字之后显示所有单词,但我不会重复,不应该重复但重复。请指导我的代码是错误的。

#! /usr/bin/perl
use strict;
use warnings;
$infile  "xyz.txt";
open (FILE, $infile) or die ("can't open file:$!");
if(FILE =~ /ENTER/ ){
    @functions = substr($infile, index($infile, 'Enter:'));
    @functions =~/@functions//;
    %seen=();
    @unique = grep { ! $seen{$_} ++ } @array;
    while (@unique != ''){
        print '@unique\n';
    }
}
close (FILE);

2 个答案:

答案 0 :(得分:2)

这是一种完成工作的方法,它会打印以关键字Enter:

开头的每行上找到的唯一字词
#!/usr/bin/perl
use strict;
use warnings;

my $infile = "xyz.txt";

# use 3 arg open with lexical file handler
open my $fh, '<', $infile or die "unable to open '$infile' for reading: $!";

# loop thru all lines
while(my $line = <$fh) {
    # remove linefeed;
    chomp($line);
    # if the line begins with "Enter:"
    # remove the keyword "Enter:"
    if ($line =~ s/^Enter:\s+//) {
        # split the line on whitespaces
        # and populate the array with all words found
        my @words = split(/\s+/, $line);
        # create a hash where the keys are the words found
        my %seen = map { $_ => 1 }@words;
        # display unique words
        print "$_\t" for(keys %seen);
        print "\n";
    }
}

答案 1 :(得分:-1)

如果我理解正确,一个问题是你的'grep'只计算每个单词的出现次数。我想你想使用'map',所以'@unique'只包含'@array'中的独特单词。像这样:

@unique = map {
    if (exists($seen{$_})) {
        ();
    } else {
        $seen{$_}++; $_;
    }
 } @array;