in reply to Re^2: Regex for removing Template::Toolkit comments?
in thread Regex for removing Template::Toolkit comments?

#!/usr/bin/perl # https://perlmonks.org/?node_id=1221039 use strict; use warnings; my $someTTstring = <<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($someTTstring); sub stripcomments { @_ and local $_ = shift; my $answer = ''; $answer .= /\G\[\%#/gc ? stripcomments() x 0 : /\G\[\%/gc ? '[%' . stripcomments() =~ s/#.*//gr . '%]' : /\G\%\]/gc ? return $answer : /\G./gcs ? $& : return $answer while 1; }

Like this?

Replies are listed 'Best First'.
Re^4: Regex for removing Template::Toolkit comments?
by bliako (Abbot) on Aug 27, 2018 at 10:41 UTC

    In my attempts I have omitted @_ and and was getting Use of uninitialized value $_, but forgotten about when you call it later on without any params. So, that works for multiline comments but not single line. I have put the following test input which I presume is valid Template::Toolkit comment syntax with the exception of nested comments which I am not sure. I will go the Parser way haukex posted. thanks

    [%# comment nust be removed 1 %] [% # comment nust be removed 2 must stay 0 %] [% # comment nust be removed 3 must stay 1 %] [% # comment nust be removed 4 must stay 2 # comment nust be removed 5 [%# nested comment (not sure if allowed or not) 1 %] %] [%# comment nust be removed 6 comment nust be removed 7 comment nust be removed 8 [%# nested comment (not sure if allowed or not) 2 %] %] [% # comment nust be removed 9 [% comment nust be removed 10 %] [% # nested comment (not sure if allowed or not) 2 %] %] [% must stay 3 %] [% must stay 4 must stay 5 # comment nust be removed 11 %] [% # comment nust be removed 12 must stay 6 %]

      Both

      comment nust be removed 9

      and

      comment nust be removed 10

      are incorrect, they should both stay under the rules you posted.

        sorry, yes you are right

        [% # this is a comment to the end of line foo = 'bar' %] [%# placing the '#' immediately inside the directive tag comments out the entire directive %]
        (http://www.template-toolkit.org/docs/modules/Template.html#section_COMMENTS)