%h = hash, $key = keys in …

%h = hash, $key = keys in %h


Sort by key

# if key is int  
    # ascending  
    for $key (sort keys %hash) {say "$key: $hash{$key}";}  

    # descending  
    for $key (reverse sort keys %hash) {say "$key: $hash{$key}";}  

# if key is str (represent number)  
    # ascending  
    for $key (sort {$a <=> $b;} keys %h) {say "$key: $h{$key}";}  

    # descending  
    for $key (sort {$b <=> $a;} keys %h) {say "$key: $h{$key}";}  

Sort by value (int)

    # value of %h is int ($h{$key})  
    # ascending order  
    for $key (sort {$hash{$a} <=> $hash{$b};} keys %h) {say "$key: $h{$key}";}  

    # descending order  
    for $key (sort {$hash{$b} <=> $hash{$a};} keys %h) {say "$key: $h{$key}";}  

Share


Donation

如果覺得這篇文章對你有幫助, 除了留言讓我知道外, 或許也可以考慮請我喝杯咖啡, 不論金額多寡我都會非常感激且能鼓勵我繼續寫出對你有幫助的文章。

If this blog post happens to be helpful to you, besides of leaving a reply, you may consider buy me a cup of coffee to support me. It would help me write more articles helpful to you in the future and I would really appreciate it.


Related Posts