By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,773 Members | 1,724 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,773 IT Pros & Developers. It's quick & easy.

Undefined Arrays inside for loop

P: 30

Im working on a Hotel Reservtion script and ran into a little problem:
I have 3 types of rooms, 1 is Single, 2 is Double, 3 is Suite
for this reason, $totaltypes = '3'; (in the snippet below).

I have a form with checkboxes in order to reserve rooms, all rooms that are checked are saved in the array @All_Rooms as detailed below:

Expand|Select|Wrap|Line Numbers
  1.  = ("1-101", "1-102","2-201", "2-202","3-301", "3-302");
1-101 means that room number 101 belongs to type 1 (being a single room).
2-201 means that room number 201 belongs to type 2 (being a double room).
and so forth.

Now I need to remove all room numbers from the array @All_Rooms and put them in separate arrays by room type. In other words all rooms beginning with 1- would go in one array, all rooms beginning with 2- would go on another, and so forth.

Except I never know how many room types will be, the script checks out this number by veryfying how many room type files have been created and assign it to the scalar $totaltypes.
I tryed the following code but it doesnt work... what am I doing wrong..??
Expand|Select|Wrap|Line Numbers
  1. for($b=1; $b<=$totaltypes; $b++)
  2. {
  3. foreach $room (@all_rooms){
  4. @splitted_room = split (/\-/, $room);
  5. if($splitted_room[0] == $b){
  6. push(@Reserved_Rooms[$b], $splitted_room[1]);
  7. }
  8. }
  9. }
Thanx beforehand
Mar 28 '09 #1
Share this Question
Share on Google+
2 Replies

Expert 2.5K+
P: 4,059
Your best option to me sounds like using a hash of arrays. The type is the hash key and all the room numbers of that type will be the value of the key, which is an array. Something like:

Expand|Select|Wrap|Line Numbers
  1. my %Rooms;
  2. foreach my $room (@all_rooms){
  3.    my ($t, $r) = split (/-/, $room);
  4.    push @{$Rooms{$t}}, $r;
  5. }
You then loop through the hash keys and the value of each hash key will have all the rooms associated with the type.

Expand|Select|Wrap|Line Numbers
  1. foreach my $type (keys %Rooms) {
  2.    print "Room Type: $type\n";
  3.    print "Rooms: ", join(' - ', @{$Rooms{$type}} , "\n\n";
  4. }
Mar 28 '09 #2

P: 30
Thank you.. I had never seen a hash of arrays... it worked

Expand|Select|Wrap|Line Numbers
  1. my %Rooms;
  2. foreach my $room (@all_rooms){
  3.    my ($t, $r) = split (/-/, $room);
  4.    push @{$Rooms{$t}}, $r;
  5. }
Apr 13 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.