2012-04-19 85 views
0

我有一個代碼如下解析一個文本文件。在文本文件的所有行上顯示「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); 
+0

您可能需要添加一些換行符開始行找到獨特的語言來碼。 ;) – oalders 2012-04-19 15:14:43

+2

這對於嚴格的編譯指令是如何工作的? – gpojd 2012-04-19 15:18:44

+0

哦,好的。那麼需要修改哪些內容才能工作? – ramki067 2012-04-19 15:20:02

回答

-1

如果我理解正確的話,一個問題是,你的「grep」可以只計算每個單詞的出現。我認爲你想使用'地圖',以便'@unique'只包含'@array'中的獨特單詞。事情是這樣的:

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

好吧,喂。完全忘記了List :: Util(並且在CORE中!)感謝您指出了這一點。 – 2012-04-21 19:03:38

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

@downvoter:有什麼理由? – Toto 2012-04-19 16:55:17