my %hash; # hash of hashes already defined and filled in an earlier part of code foreach (sort keys %{$hash{$key1}}){ if ($hash{$key1}{$_}=~ /^.+_(\d+)_.+AAA/gi){ print "found1\n"; } if ($hash{$key1}{$_}=~ /^.+_(\d+)_.+BBB/gi){ print "found2\n"; } if ($hash{$key1}{$_}=~ /^.+_(\d+)_.+CCC/gi){ print "found3\n"; } } #### found2 found3 found2 found3 ... #### foreach (sort keys %{$hash{$key1}}){ if ($hash{$key1}{$_}=~ /^.+_(\d+)_.+AAA/gi){ print "found1\n"; } # copied from above and changed the output to 'foundx' if ($hash{$key1}{$_}=~ /^.+_(\d+)_.+AAA/gi){ print "foundx\n"; } # if ($hash{$key1}{$_}=~ /^.+_(\d+)_.+BBB/gi){ print "found2\n"; } if ($hash{$key1}{$_}=~ /^.+_(\d+)_.+CCC/gi){ print "found3\n"; } } #### foundx found2 found3 foundx found2 found3 ...