我正在尝试从文件中读取并打印出每行上重复单词的位置。我已将每行存储在一个数组中,但我不确定这是否是正确的启动方式。
while (my $fileLine = <$fh>){
my @lineWords = split /\s+/, $fileLine;
print "@\n"
}
答案 0 :(得分:1)
#!/usr/bin/perl
use strict;
use warnings;
while (<DATA>){
chomp; # remove end of line chars
my @wordsInLine = split /\s+/, $_;
@wordsInLine = map {lc($_)} @wordsInLine; # convert words to lowercase
my( $word, %wordsInLine, $n );
for $word (@wordsInLine) {
$wordsInLine{$word}++; # use hash %wordsInLine to count occurences of words
}
for $word (@wordsInLine) {
$n++;
if( (my $count = $wordsInLine{$word}||0) > 1 ) {
print "line $.: Word $n \"$word\" is repeated $count times\n";
delete($wordsInLine{$word}); # do not generate more than one report
# about the same word in single line
}
}
}
__DATA__
This this is a sample sentence
A that That THAT !