I have the following data structure:
$data_hash{$key0}[$idx0]{$key1} = <some floating point value>
I would like to sort this data structure by its values. Currently I am doing this by creating a new hash in which the key is the floating point value, and the value is an array where each element is a concatenation of $key0, $idx0, and $key1. Each value of the new hash has to be an array as opposed to a scalar because the floating point values in the original data structure are not guaranteed to be unique; that is two entries in the original hash of array of hashes could have the same value.
Is there a way to sort this data structure by value without having to create a new hash first? I figure there must be some way to use the sort command with the original data structure, but I can't seem to get it to work. Also if there is a way to sort my original data structure by value using a single sort command, are there any performance implications by doing so compared to the method I am currently using?
Here is the method I am currently using if anyone is curious:
# create a new hash where the key is the value of the original hash, a
+nd the value is an array of keys from the original hash that have the
+ given value
foreach $key0 (keys(%data_hash))
{
foreach $key1 (keys(%{$data_hash{$key0}}))
{
for ($i = 0; $i < @{$limit_hash{$key0}{$key1}{'limit'}}; $i++)
{
push(@{$new_hash{$data_hash{$key0}[$i]{$key1}}}, $key0 . "
+__" . $limit_hash{$key0}{$key1}{'limit'}[$i] . "__" . $key1);
}
}
}
# now print the new hash that is sorted by value
foreach my $sorted_by_val ( sort{$a <=> $b} keys(%new_hash))
{
printf("key %.2f: ", $sorted_by_val);
foreach my $val (@{$new_hash{$sorted_by_val}})
{
printf("$val");
}
printf("\n");
}
-
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.
|