#!/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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.