2012-04-19 16 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

+2

これはstrictプラグマを使用してどのように動作しますか? – gpojd

+0

よろしいですか?どのような作業をするために変更する必要がありますか? – ramki067

答えて

-1

私が正しくあなたを理解していれば、一つの問題は、あなたの「grepのは」のみ、各単語の出現をカウントしていることです。私は '@ユニーク'には '@array'のユニークな単語しか含まれないように 'マップ'を使いたいと思う。このような何か:

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

まあ、ダン。 List :: Utilを忘れてしまった(とCOREでも!)それを指摘してくれてありがとう。 –

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

関連する問題