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);
4

2 回答 2

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";
    }
}
于 2012-04-19T15:50:35.060 回答
-1

如果我理解正确,一个问题是您的“grep”只计算每个单词的出现次数。我认为您想使用“地图”,以便“@unique”仅包含“@array”中的唯一单词。像这样的东西:

@unique = map {
    if (exists($seen{$_})) {
        ();
    } else {
        $seen{$_}++; $_;
    }
 } @array;
于 2012-04-19T15:44:51.433 回答