while( $file =~ /\Q$start\E(.*?)\Q$end\E/sg ) { $a = $1; $match = $&; #look for more start tags in what we matched while( $a =~ /\Q$start\E/sg ) { #balance the ending comments $file =~ /.*?\Q$end\E/sg; $match .= $&; } print $match, "\n"; }