misterperl has asked for the wisdom of the Perl Monks concerning the following question:

I'm thinking this might be possible?
my %h = qw (1 cat 2 dog 3 mouse 4 fish ); my %sortH; @sor4tH( sort values %h } = ?
Is there some simple value of ? that would satisfy the corresponding list of hash values?

TYVM, Respect!

Replies are listed 'Best First'.
Re: Is there a way to switch a hash values <> keys with a slice?
by Fletch (Bishop) on Apr 19, 2022 at 14:04 UTC

    For one thing you're committing a thinko in that a hash is by definition unordered (unless you do some tie magic under the hood) so your destination is misnamed. That being said since keys and values will return things in the same order so long as you don't change the underlying hash you can swap things the obvious way.

    main::(-e:1): 0 DB<1> %foo = qw( a b c d ) DB<2> @bar{ values %foo } = keys %foo DB<3> x \%bar 0 HASH(0x7fb23c8b94b8) 'b' => 'a' 'd' => 'c'

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Is there a way to switch a hash values <> keys with a slice?
by LanX (Saint) on Apr 19, 2022 at 14:21 UTC
    reverse is your friend, but hashes have no order so your sort is for vain. .

    main::(-e:1): 0 DB<1> @h{ a..c } = 1..3 DB<2> x \%h 0 HASH(0x33c38e0) 'a' => 1 'b' => 2 'c' => 3 DB<3> %h2 = reverse %h DB<4> x \%h2 0 HASH(0x3554090) 1 => 'a' 2 => 'b' 3 => 'c' DB<5>

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

      thank you both! YEs makes sense I musta needed more coffee today!
        you should also keep in mind that hash-keys are unique, any repeated value from the old hash will overwrite the last key-instance in your reversed hash.

        (the only way to avoid information loss is a hash of arrays $h2{val}=[k1,k2,k3,...] but this requires more code.)

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery

Re: Is there a way to switch a hash values <> keys with a slice?
by BillKSmith (Monsignor) on Apr 19, 2022 at 16:06 UTC
    You have received a few suggestion on how to 'invert' a hash. Note that these only work if no value is repeated in the original hash. A more general solution can be found in the very old book "Perl Cookbook". There probably is a module, but I did not find it with a quick search.

    Note: Although it is not possible to sort your hash, it is possible to access it in a sorted order. See FAQ How do I sort a hash (optionally by value instead of key)?

    Bill