$string = "This is bLarney rubble and his friends joe rockhead and fred flintstone"; $count = 0; for $target (qw(fred barney joe)) { if ( $string =~ /(?=.*\b$target (\w+))/i ) { push @elements, $1; $count++; } else { push @elements, ''; # as a placeholder } } if ($count >= 2) { print join('_', @elements), "_inc\n" } else { print "Didn't find at least 2 elements in the string\n" } # prints flintstone__blockhead_inc # change 'joe' to 'moe' and you get > Didn't find at least 2 elements in the string