2

Right, so I've gotten some help but need some more, I have a pretty good understanding on how to sort an array alphabetically. But now I need to sort it numerically. It's probably a syntax error near "my @test = (sort {items{$a}} <=> {items{$b}} @menu)"

Had it been a hash with two keys I would have a solution, but since this array contains three categories it becomes difficult for me. Obviously looking for some help along with an explanation as possible as I'm eager to learn. Thank you!

my @test = (sort {price{$a} <=> {price{$b}} @menu)
2
  • Also if someone could point me to some reading that explains it would be very appreciated, as my luck with google on this topic seems exhausted. Commented Mar 16, 2015 at 21:47
  • 1
    ad google, try: perl sort array of hashes by multiple values and check first NN links.. ;) Commented Mar 16, 2015 at 21:51

2 Answers 2

2

The issue is item{$a}. It looks like you are trying get some value from hash item which is not a hash, of course.

my @test = sort { $a->{price} <=> $b->{price} } @menu;

You can sort according more than one field as well

my @test = sort {
           $a->{price} <=> $b->{price}
        or $a->{color} cmp $b->{color}
        or $b->{items} cmp $a->{items} # note reverse order
    } @menu;
Sign up to request clarification or add additional context in comments.

2 Comments

This is honestly just plain annyoing. I swear to god I've tried that exact syntax on price earlier but it did not return the right result. However now it does.. Thank you!
@pubba Note the difference between cmp (for strings) and <=> (for numbers).
0

This is how to order by prize:

my @test = sort { $a->{prize} <=> $b->{prize} } @menu;

and in descending order, just change $a and $b:

my @test = sort { $b->{prize} <=> $a->{prize} } @menu;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.