看不懂,求解!

看不懂,求解!

#!/usr/bin/perl


while ($line = <STDIN>){
    
    $line =~ tr/A-Z/a-z/;
    $line =~ s/[^a-z]//g;
    @letters=split(//,$line);
    foreach $letter (@letters){
        $lettercount{$letter}+=1;
    }
}

$~="WRITEHEADER";
write;
$count =0;
foreach $letter (reverse sort occurrences(keys(%lettercount))){
    &write_letter($letter,$lettercount{$letter});
    last if (++$count ==5);
}

sub occurrences{
    $lettercount{$a}<=>$lettercount{$b};
}

sub write_letter{
    local($letter,$value)=@_;
    $~="WRITELETTER";
    write;
}

format WRITEHEADER =
The five most frequently occurring letters are:
.
format WRITELETTER =
  @: @<<<<<<
  $letter, $value
.



其中 :

foreach $letter (reverse sort occurrences(keys(%lettercount))){
        &write_letter($letter,$lettercount{$letter});
        last if (++$count ==5);
}

sub occurrences{
        $lettercount{$a}<=>$lettercount{$b};
}

看不懂,求解?occurrences 什么作用?

对lettercount这个hash的键进行升序排列
xiexie,是按值排列。

测试代码:

#!/usr/bin/perl



print ("\t统计字符出现次数\n请输入英文字符:回车ctl+d 结束输入:\n");
while ($line = <STDIN>){
    
    $line =~ tr/A-Z/a-z/;
    $line =~ s/[^a-z]//g;
    @letters=split(//,$line);
    foreach $letter (@letters){
        $lettercount{$letter}+=1;
    }
}
$i=0;
sub occurrences{
    #print ("调用第[".++$i."]次:$a=>$lettercount{$a} $b=>$lettercount{$b}\n");

    $lettercount{$a}<=>$lettercount{$b};
}
print ("\n原始哈希表元素列表 :\n");
while (($key, $var) = each(%lettercount)) {
  print ("$key=>$var\n");
}
print ("\n哈希表按字符排序:\n");
foreach $word (sort keys(%lettercount)) {
    print ("$word=>$lettercount{$word}\n");
    }
print("\n按字符出现次数排序\n");
foreach $word (reverse sort occurrences(sort keys(%lettercount))) {
        print ("$word=>$lettercount{$word}\n");
    }




QUOTE:
原帖由 chinaorg 于 2008-11-24 23:23 发表
sub occurrences{
        $lettercount{$a}<=>$lettercount{$b};
}

看不懂,求解?occurrences 什么作用?

perldoc -f sort
reverse sort occurrences(keys(%lettercount))这么写有点傻,直接写成密名函数看着就清楚多了