Sort and Print Multidimensional Hash

L

Larry

Hi!,

I have a multi dimensional hash made up like this below:

my $global = {};
$global->{"KEY1"}->{"ID"} = k;
$global->{"KEY1"}->{"VALUE1"} = "...";
$global->{"KEY1"}->{"VALUE2"} = "...";

$global->{"KEY2"}->{"ID"} = k;
$global->{"KEY2"}->{"VALUE1"} = "...";
$global->{"KEY2"}->{"VALUE2"} = "...";

Now I'd like to sort it by ID (0..1) then print it, is there an easy way to
do that?

thanks
 
J

Jürgen Exner

Larry said:
Hi!,

I have a multi dimensional hash made up like this below:

my $global = {};
$global->{"KEY1"}->{"ID"} = k;
$global->{"KEY1"}->{"VALUE1"} = "...";
$global->{"KEY1"}->{"VALUE2"} = "...";

$global->{"KEY2"}->{"ID"} = k;
$global->{"KEY2"}->{"VALUE1"} = "...";
$global->{"KEY2"}->{"VALUE2"} = "...";

Now I'd like to sort it by ID (0..1) then print it, is there an easy way to
do that?

No, the way you stated your question it is impossible because hashes do
not have an order and therefore cannot be sorted.

However, if you rephrase your question in a more meaningful way like
e.g. "how can I sort the keys of %global such that they are sorted by
the value of ID", then the challenge becomes trivial to solve:
Just sort() the keys() of %global, using {$global->$_->'ID'} as the
compare function for sort().

And then loop through the the sorted keys and print the associated hash
elements in that order.

jue
 
J

Jürgen Exner

Jürgen Exner said:
No, the way you stated your question it is impossible because hashes do
not have an order and therefore cannot be sorted.

However, if you rephrase your question in a more meaningful way like
e.g. "how can I sort the keys of %global such that they are sorted by
the value of ID", then the challenge becomes trivial to solve:
Just sort() the keys() of %global, using {$global->$_->'ID'} as the
compare function for sort().

Actually, this is very poorly worded, let me rephrase:
.... comparing $global->$a->'ID' and $global->$b->'ID' in the compare
function for sort().

jue
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top