View Full Version : error when looping through hash.

11-06-2009, 05:00 AM

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?

Can't use string ("1") as a HASH ref while "strict refs" in use at .... line 223

'product_id_room' => {
'46' => '1',
'48' => '3',
'47' => '2'

here is my loop

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 />);


Then I read about perl not liking single digit numbers in these circumstances so I found this bit of code. Is it correct? It seems to work but I would like the best way to do it.

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 );


11-06-2009, 05:39 PM
use <=> operator instead of cmp when you compare numbers

sort { $product_id_room_numbers{$a} <=> $product_id_room_numbers{$b} } keys %product_id_room_numbers;

best regards

11-06-2009, 07:40 PM
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. :eek: