0

Perlでの私の質問は次のとおりです。テキストを読み取り(句読点や数字なし)、ソートされた単語のリストとそれぞれがテキストに出現する回数を出力するPerlスクリプト。私のスクリプトは次のとおりです。

#!/usr/bin/perl
@names = qw(My name is Ashok Rao and I am the son of Shreesha Rao and Shailaja Rao);
join(',',@names);
my %count;
foreach (@names)
{
 if (exists $count{$_}) 
 {
  $count{$_}++;
 } 
 else
 {    
  $count{$_} = 1;
 }
}
my @order = sort(@names);
print "The words after sorting are:\n";
print "@order\n";
print "The number of times each word occurring in the text is: \n";
foreach (keys %count) 
{
 print "$_ \t = $count{$_}\n";
}

出力は次のとおりです。

The words after sorting are:
Ashok I My Rao Rao Rao Shailaja Shreesha am and and is name of son the
The number of times each word occurring in the text is:
the = 1
son = 1
of = 1
name = 1
Ashok = 1
Shailaja = 1
is = 1
Rao = 3
am = 1
My = 1
I = 1
and = 2
Shreesha = 1

しかし、SORTING部分の出力は間違っていると思います。単語出現部分の出力は正しいです。助けてください。前もって感謝します

4

2 に答える 2

3

perlは小文字と大文字を区別します。ucandlc関数を使用して、文字列を大文字または小文字に変換できます。

于 2012-10-17T11:34:54.750 に答える
0

他の人が指摘しているように、問題は、語順ではなく、ASCII文字コードによってソートが行われていることです。これは、すべての大文字の単語がすべての小文字の単語に続くことを意味します。これを解決するには、sort関数を呼び出すときに独自の比較を指定するだけです。

my @order = sort {lc $a cmp lc $b} @names;

比較の両側を小文字にすることで、正しいアルファベット順が可能になります。

于 2012-10-17T11:55:40.680 に答える