sort hash values does not work

F

fatgirl.brown

Hi, I have a two-dim array as hash value and I want to sort it:

# <code>
#!/usr/bin/perl -w

push @{$hash{"test"}}, [10, "hi1"];
push @{$hash{"test"}}, [3, "hi2"];
push @{$hash{"test"}}, [5, "hi3"];
push @{$hash{"test"}}, [1111, "hi4"];

@{$hash{"test"}} = sort {$a <=> $b} @{$hash{"test"}};
print join " ", @{$hash{"test"}[0]};
print "\n";
# </code>

But it prints "5 hi3". So it put the 5 first, although the 3 should be
first after it's sorted. How can I sort so that it's 3, 5, 10, 1111?

Thanks!!
Junupa
 
X

Xicheng Jia

Hi, I have a two-dim array as hash value and I want to sort it:

# <code>
#!/usr/bin/perl -w

push @{$hash{"test"}}, [10, "hi1"];
push @{$hash{"test"}}, [3, "hi2"];
push @{$hash{"test"}}, [5, "hi3"];
push @{$hash{"test"}}, [1111, "hi4"];

@{$hash{"test"}} = sort {$a <=> $b} @{$hash{"test"}};

here you are comparing two array references, to compare based on one of
their elements, you may want to dereference them, like:

@{$hash{"test"}} = sort { $a->[0] <=> $b->[0] } @{$hash{"test"}};

Xicheng
 

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

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top