while () { my ($key2,$data) = split(/,/, $_, 2); # use grep to do the "join": my @match_keys = grep { my ($sid,$eid) = split(/ /,$_); $key2 >= $sid and $key2 <= $eid } keys %VAR1; foreach my $matched_range ( @match_keys ) { my @matched_data = @{$VAR1{$matched_range}}; # do something with @matched_data } }