my $piece; foreach (keys %Words_db) { if ( ... ) { # if $piece is a substring of $_ ... } else { $piece does not occur in $_ ... } }