for my $key ( sort keys %title ) { #### # This will sort by title, then by topic id sub by_course_and_title { return $title{$a}{il2e002_course_title_x} cmp title{$b}{il2e002_course_title_x} || $title{$a}{il2e002_topic_id_k} cmp title{$b}{il2e002_topic_id_k}; } for my $key ( sort &by_course_and_title keys %title ) { #### for my $foo ( @foo ) { # Do something interesting }