in reply to Navigating in hash of hash

Given that you are "sitting at" a particular lesson, do you only need to go to the "next" lesson, or do you also need to be able to go back to the "previous" lesson? You probably need to set up linkages in your hash structure, and it's just a question whether you need the linkage to just go one way, or both ways.

For the one-way case (link to next), you can set up the linkage by doing a foreach loop in reverse order:

my $next; # defaults to "undef" for my $unit ( sort { $b cmp $a } keys %available_data ) { for my $lesson ( sort { $b cmp $a } keys %{$available_data{$unit}} + ) { $available_data{$unit}{$lesson} = $next; $next = "$unit $lesson"; } }
That way, for any specific values of "unit" and "lesson", the hash just stores the values of the "next" unit and lesson, and you just have to split that value on the space character in order to look up that location in the hash. When the value is undef, it means there is no "next" lesson.

If the hash is supposed to store something else (besides "undef") as the content for each lesson, just add another layer to the hash structure, with "content" and "next" as the keys at that level. (Likewise, if you have to store linkage in both directions, have "next" and "prev" as keys for storing the "unit lesson" values, as well as a "content" key, if needed.)

Replies are listed 'Best First'.
Re^2: Navigating in hash of hash
by Dirk80 (Pilgrim) on Nov 05, 2009 at 11:34 UTC
    Thank you a lot for your ideas. At the end I took the solution of graff. It is working fine. Here my code:
    my $unit; my $lesson; my $next; # defaults to "undef" $available_data{'02'}{'03'} = undef; $available_data{'02'}{'05'} = undef; $available_data{'02'}{'11'} = undef; $available_data{'05'}{'02'} = undef; $available_data{'05'}{'03'} = undef; $available_data{'07'}{'01'} = undef; $available_data{'07'}{'04'} = undef; $available_data{'07'}{'07'} = undef; $available_data{'07'}{'08'} = undef; for $unit ( sort { $b cmp $a } keys %available_data ) { for $lesson ( sort { $b cmp $a } keys %{$available_data{$u +nit}} ) { $available_data{$unit}{$lesson}{'next'} = $next; $next = "$unit-$lesson"; } } # Unit 05, Lesson 03 --> Unit 07, Lesson 01 $unit = "05"; $lesson = "03"; print "Unit " . $unit . ", Lesson " . $lesson . " --> Unit " . substr($available_data{$unit}{$lesson}{'nex +t'}, 0, 2) . ", Lesson " . substr($available_data{$unit}{$lesson}{'next +'}, 3, 2) . "\n";

      perldsc might be helpful in the future too...

      Just a something something...