@Lines = ( "fred flinstones barney rubble joe rockhead", "fred flinstones joe rockhead barney rubble", "barney rubble fred flinstones joe rockead", "barney rubble joe rockhead fred flinstones", "joe rockhead fred flinstones barney rubble", "joe rockead barney rubble fred flinstones", ); $LineNum = 0; foreach $Line (@Lines) { ++$LineNum; @Match = (); undef ($Company); @Match = $Line =~ /(?:\b(?:fred|barney|joe)\s+(\w+))+/g; $Company = join ("_", @Match) . '_inc' if (@Match); ($Company) ? (print "[$LineNum]: Company = $Company\n"): (next); }