http://qs1969.pair.com?node_id=1181901

#!/usr/bin/perl # Program name: next-value-of-hash.pl Run it, thusly: perl next-value +-of-hash.pl Look at the next value of hash when sorting by values # From perlmonks Chatterbox 20170213 reply by [ambrus] # [stu96art] I am hoping to get some help with hashes. Working on l +ooking at the next value when sorting by values, but don't know how t +o reference it. # [stu96art] My code is on my scratchpad: /padstu96art # [ambrus] stu96art: perhaps try to first assign the sorted key lis +t to an array variable, then iterate through that array with indexes # [stu96art] Gotcha. That makes sense. Appreciate the help. # [ambrus] like my@s = sort keys %a; for my$i (keys@s) { print "cur +rent: $s[$i] => $a{$s[$i]}, next: ", ($i+1<@s ? "$s[$i+1] => $a{$s[$i ++1]}" : "none"); } # [stu96art] Thanks again. I will work on that. use strict; use warnings; # Example hash from https://perlmaven.com/perl-hashes my %color_of = ( "apple", "red", "orange", "orange", "grape", "purple", "tomato", "red", "lettuce", "green", "peanut", "tan", ); my @s = sort keys %color_of; for my $i ( keys @s ) { print "current: $s[$i] => $color_of{$s[$i]}, next: ", ( $i + 1 < @s ? "$s[$i+1] => $color_of{$s[$i+1]}" : "none" ); print "\n"; } __END__

Close readers will note the following: stu96art specified "when sorting by values".

It is debatable whether he meant Sort the values of the hash or Sort the hash in alphabetical order of its keys.

https://perlmaven.com/how-to-sort-a-hash-in-perl is a good place to start to learn this particular subject.

Replies are listed 'Best First'.
Re: Look at the next value of hash when sorting by values
by choroba (Archbishop) on Feb 13, 2017 at 17:31 UTC
    Or just keep the previous value in a variable. I'd understand "sorting by values" as walking the hash keys in the order of the values.
    #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; my %color_of = ( apple => 'red', orange => 'orange', grape => 'purple', tomato => 'red', lettuce => 'green', peanut => 'tan', ); my $previous; for my $fruit_or_vegetable ( sort { $color_of{$a} cmp $color_of{$b} } keys %color_of ) { say "$previous before $fruit_or_vegetable" if defined $previous; $previous = $fruit_or_vegetable; }
    ($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,
Re: Look at the next value of hash when sorting by values
by Laurent_R (Canon) on Feb 13, 2017 at 23:16 UTC
    Sorting the values of the hash is trivially simple, sorting the keys also, I would agree with choroba that stu96art probably wants to sort the keys in accordance with the alphabetical (or other) order of the values (which is slightly more involved).