for my $query( sort keys %data ) { # get all the lines of the query at once, into an array: my @query_lines = @{$data{$query}}; # or iterate over them: for my $qline ( @{$data{$query}} ) { # ... do something with the line. } # or, if you really care about the line numbers: for my $li ( 0 .. $#{$data{$query}} ) { my $qline = $data{$query}[$li]; print "query $query, line $li: $qline"; } }