while ($A =~ m{(.+)}g) { my $capture = $1; $B .= "$capture\n" if $capture =~ /def/; }