![]() |
|
|
|||||||
![]() |
|
|
Thread Tools | Rate Thread |
|
|
PM User | #1 | |
|
Senior Coder ![]() Join Date: Apr 2003
Location: in my house
Posts: 4,330
Thanks: 35
Thanked 151 Times in 147 Posts
![]() ![]() |
error when looping through hash.
Hi,
Getting the hang of hashes now (yay!) but have got stuck. I have a working solution at the end of this post but is it the best way? my hash, retrieved from session, is like shown below and my two foreach loops throw an error. (also shown). How can I output the room numbers in order, without getting this error? Quote:
Code:
'product_id_room' => {
'46' => '1',
'48' => '3',
'47' => '2'
},
Code:
foreach my $product_id (sort keys %product_id_room_numbers) {
foreach my $room_number (sort keys % {$product_id_room_numbers{$product_id}}) {
print qq( product_id=$product_id :: room_number = $room_number <br />);
}
}
Code:
foreach my $product_id (sort {$product_id_room_numbers{$a} cmp $product_id_room_numbers{$b} }
keys %product_id_room_numbers) {
my $room_number = $product_id_room_numbers{$product_id};
print qq(
product_id = $product_id : room_number = $room_number );
__________________
"The day you stop learning is the day you become obsolete"! - my late Dad. Useful MySQL resource Useful MySQL link |
|
|
|
|
|
|
PM User | #2 |
|
Senior Coder ![]() ![]() Join Date: Dec 2007
Posts: 4,658
Thanks: 374
Thanked 562 Times in 551 Posts
![]() ![]() |
use <=> operator instead of cmp when you compare numbers
Code:
sort { $product_id_room_numbers{$a} <=> $product_id_room_numbers{$b} } keys %product_id_room_numbers;
|
|
|
|
|
|
PM User | #3 |
|
Senior Coder ![]() Join Date: Apr 2003
Location: in my house
Posts: 4,330
Thanks: 35
Thanked 151 Times in 147 Posts
![]() ![]() |
Thank you oesxyl,
I wondered about that but I thought the website I visited (tutorial), was more knowledgable than me so I used their suggestion. Time to trust my own sense. ![]() bazz
__________________
"The day you stop learning is the day you become obsolete"! - my late Dad. Useful MySQL resource Useful MySQL link |
|
|
|
![]() |
| Bookmarks |
| Thread Tools | |
| Rate This Thread | |
|
|