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 回答