Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Custom, Reusable Sort Subroutine for Hashes?

by choroba (Cardinal)
on Aug 30, 2017 at 11:09 UTC ( [id://1198324]=note: print w/replies, xml ) Need Help??


in reply to Custom, Reusable Sort Subroutine for Hashes?

#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; sub sort_hash (&\%) { my ($sub, $hash) = @_; sort { local($a, $b) = @$hash{$a, $b}; $sub->() } keys %$hash } my %hash = ( second => 2, fourth => 4, third => 3, first => 1 ); say for sort_hash { $a <=> $b } %hash;

I used a prototype to make the syntax of sort_hash similar to that of sort. The trick is replacing the magical variables $a and $b with the respective values from the hash.

Update: explanation added.

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Replies are listed 'Best First'.
Re^2: Custom, Reusable Sort Subroutine for Hashes?
by QM (Parson) on Aug 30, 2017 at 12:45 UTC
    This is very good, thanks.

    Just as an extension, can I use this with a named sort sub? I expect so, but I'll have to go off and experiment.

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

      > can I use this with a named sort sub?

      Sure, but you can't use the nice syntax anymore:

      sub numerically { $a <=> $b } say for sort_hash(\&numerically, %hash);
      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
        > but you can't use the nice syntax anymore:

        > say for sort_hash(\&numerically, %hash);

        well you don't need the braces

        say for sort_hash \&numerically, %hash ;

        and this works too

        say for sort_hash {numerically} %hash ;

        Cheers Rolf
        (addicted to the Perl Programming Language and ☆☆☆☆ :)
        Je suis Charlie!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1198324]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2025-06-23 12:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.