Perl发现重复(抛光现有代码)

时间:2014-07-29 18:36:18

标签: perl duplicates editing

嘿所有以下是我的代码:

#!/bin/usr/perl

@words = ();
@dup = ();

print "Please enter your query sentence:\n";
$input = <STDIN>;
chomp $input;

@words = split(/ /, $input);
@sort  = sort { "\L$a" cmp "\L$b" } @words;
for $n ( 0..$#sort ) {
   if (lc $sort[$n] eq lc $sort[($n+1)]) {
      push (@dup, $sort[$n]);
   }
   else {
      $n+=1;
   }
 }

 if ( @dup == () ) { 
    print "There are no duplicates in the query sentence.\n";
 }
 else {
    print "@dup \n";
 }

我遇到的问题是,如果单词出现的次数超过了@dup中每次出现的次数。我该如何解决?在此先感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

使用Hash会更简单,它仍然可以让你跟踪重复项并使你无需预先分配数组:

use strict;
use warnings; 

print "Please enter your query sentence:\n";
my $input = <STDIN>;
chomp $input;
my @words = split /\s+/, $input;

my %unique_elems;
for my $word ( @words ) {
   $unique_elems{$word}++;
}

if ( scalar keys %unique_elems == scalar @words ) { 
   print "There are no duplicates in the query sentence.\n";
}
else {
   my @dups = grep { $unique_elem{$_} > 1 } keys %unique_elems;  
   print join ',', @dups;
   print "\n";
}

一对夫妇注意到:

  1. 你应该始终use strict; use warnings;在脚本的顶部,它会比你想象的更省时间
  2. 您应该使用my声明词法变量而不是声明全局变量

答案 1 :(得分:0)

使用此:

#!/bin/usr/perl
@words = ();
@dup = ();
print "Please enter your query sentence:\n";
$input = <STDIN>;
chomp $input;
@words = split(/ /, $input);
@sort= sort {"\L$a" cmp "\L$b"}@words;
%hash;
for $n (0..$#sort) {
        if (lc $sort[$n] eq lc $sort[($n+1)]) {
                if(!defined $hash{$sort[$n]}) {
                    push (@dup, $sort[$n]);
                    $hash{$sort[$n]}=1;
                }
        }
        else {$n+=1;}
            }
if (@dup==()){print "There are no duplicates in the query sentence.\n";}
else {print "@dup \n";}

刚刚定义了一个额外的hash%hash来保留数组中的唯一条目。

答案 2 :(得分:0)

print "Please enter your query sentence:\n";
$input = <STDIN>;
chomp $input;
my @words = split /\s+/, $input;
my %words;
foreach my $word(@words) {
    $words{lc($word)}++;
}
my @dup = grep {$words{$_} > 1} keys %words;
if (@dup == 0) { 
    print "There are no duplicates in the query sentence.\n";
 }
 else {
    print "@dup \n";
 }