while ( $text =~ m/(.*?)<--end-->/s ) { my $chunk = $1; if ( $chunk =~ // ) { # do something with $1 } else { # do something with $chunk } }