Here's a first try at a little recursive parser that will strip nested items.
If you have a better test case (or a counter-example) please let me know.
#!/usr/bin/perl
# https://perlmonks.org/?node_id=1221039
use strict;
use warnings;
$_ = <<END;
before
[% # this is a comment to the end of line
foo = 'bar'
%]
<p>bw, bliako</p>
[%# placing the '#' immediately inside the directive
tag comments out the entire directive
%]
[% outside %]
[%# placing the '#' immediately inside the directive
tag comments out the entire directive
[% inside %]
%]
after
END
print stripcomments();
sub stripcomments
{
my $answer = '';
$answer .=
/\G\[\%#/gc ? stripcomments() x 0 :
/\G\[\%/gc ? '[%' . stripcomments() =~ s/#.*//gr . '%]' :
/\G\%\]/gc ? return $answer :
/\G./gcs ? $& :
return $answer while 1;
}
Outputs:
before
[%
foo = 'bar'
%]
<p>bw, bliako</p>
[% outside %]
after