in reply to hash sort

#!/usr/bin/perl # http://perlmonks.org/?node_id=1191725 use strict; use warnings; my %hash1; $hash1{'1'} = 1; $hash1{'2'} = 1; $hash1{'3'} = 1; $hash1{'4'} = 1; $hash1{'5'} = 1; my %hash2; $hash2{'1'}{key} = 'a'; $hash2{'2'}{key} = 'b'; $hash2{'3'}{key} = 'a'; $hash2{'4'}{key} = 'a'; $hash2{'5'}{key} = 'b'; print map $_->[2], sort { $a->[1] cmp $b->[1] or $a->[0] <=> $b->[0] } map [ $_, $hash2{$_}{'key'}, "key $_ and $hash2{$_}{'key'}\n" ], keys %hash1;

Replies are listed 'Best First'.
Re^2: hash sort
by Anonymous Monk on May 31, 2017 at 17:34 UTC
    print map $_->[2], sort { $a->[1] cmp $b->[1] or $a->[0] <=> $b->[0] } map [ $_, $hash2{$_}{'key'}, "key $_ and $hash2{$_}{'key'}\n" ], keys %hash1;
    Please explain , Cant understand. This is sample code. I have many HOH in my script. Can you please assign / push $_ value in array ? I lost it because of many map functions :( :(
      Can you please assign / push $_ value in array ?

      I think tybalt89 was just trying to tie  %hash1 into a solution in line with the structures given in your OP. I, myself, don't understand the relation of the  %hash1 and  %hash2 hashes: they seem essentially identical. See johngg's post for another approach to trying to tie these two hashes together meaningfully.

      Separating out the elements a bit, see if this is clearer:

      c:\@Work\Perl\monks>perl -wMstrict -le "my %hash1 = map { $_ => 1 } 1 .. 5; ;; my %hash2; $hash2{'1'}{key} = 'a'; $hash2{'2'}{key} = 'b'; $hash2{'3'}{key} = 'a'; $hash2{'4'}{key} = 'a'; $hash2{'5'}{key} = 'b'; ;; my @sorted_top_level_hash1_keys = map $_->[0], sort { $a->[1] cmp $b->[1] or $a->[0] <=> $b->[0] } map [ $_, $hash2{$_}{'key'} ], keys %hash1 ; print qq{sorted top-level %hash1 keys: (@sorted_top_level_hash1_keys) +}; ;; for my $stlh1k (@sorted_top_level_hash1_keys) { print qq{key $stlh1k and $hash2{$stlh1k}{key}} } " sorted top-level %hash1 keys: (1 3 4 2 5) key 1 and a key 3 and a key 4 and a key 2 and b key 5 and b


      Give a man a fish:  <%-{-{-{-<