$file = (grep{$line =~ /$_/i} @words)[0]; or foreach (@words) { next if($line !~ /$_/i); $file = $_; }