$id = $Words_db{$word}; foreach $i (keys %Index_db) { if ($i == $id) { @fileId = split( /:/, $Index_db{$i}); foreach $fId (@fileId) { # ... } } } #### my $piece; foreach (keys %Words_db) { if ( ... ) { # if $piece is a substring of $_ ... } else { $piece does not occur in $_ ... } }