perl中如何将按hash的排序方法

2024-11-06 22:29:38
推荐回答(1个)
回答1:

如果是按ASCII码排序,则代码如下:

foreach my $key ( sort { $hash{$a} cmp $hash{$b} } keys %hash ) {
my $value = $hash{$key};
# do something with ($key, $value)
}


如果是按数字小到大排列,则代码如下:

foreach my $key ( sort { $hash{$a} <=> $hash{$b} } keys %hash ) {
my $value = $hash{$key};
#do something with ($key, $value)
}

    如果是按数字大到小排列,则代码如下:

    foreach my $key ( sort { $hash{$b} <=> $hash{$a} } keys %hash ) {
    my $value = $hash{$key};
    #do something with ($key, $value)
    }

    按KEY排列

    foreach my $item (sort {$a<=>$b} keys %hash){
    print "$item  == > $hash{$item}","/n";
    }