in reply to Re^5: perl script to search and replace comment in .aspx file
in thread perl script to search and replace comment in .aspx file

i made some modification in reg exp in the code written by stevieb and it's working fine for this type of data data --- <script type="java/js"> foobie bletch </script> <%-- <script> zelgo mer </script> --> but problem is if i write endi script tag </script> not in the first column,it's not commenting or uncommenting that.

#!/usr/bin/perl use warnings; use strict; open my $fh, '<', 'hii.txt' or die "Can't open the damn file for readi +ng!: $!"; my @file_content; while ( my $line = <$fh> ){ chomp $line; if ( $line =~ /^<script(.*)>/ ){ $line = "<%-- $line"; push @file_content, "$line\n"; next; } elsif ( $line =~ /^<\/script>$/ ){ $line .= " -->"; push @file_content, "$line\n"; next; } elsif ( $line =~ /^<%--\s+<script(.*)>/ ){ $line =~ s/^<%--\s+//; push @file_content, "$line\n"; next; } elsif ( $line =~ /^<\/script>\s+-->/ ){ $line =~ s/\s+-->//; push @file_content, "$line\n"; next; } push @file_content, "$line\n"; } close $fh; open $fh, '>', 'hii.txt' or die "Can't open the damned file for writin +g: $!"; print $fh @file_content; close $fh;

Replies are listed 'Best First'.
Re^7: perl script to search and replace comment in .aspx file
by Corion (Patriarch) on Jun 08, 2012 at 09:35 UTC

    Maybe now would be a good moment to look at perlre to learn about how the regular expression matching </script> works. YAPE::Regex::Explain contains the explain tool that does that:

    The regular expression: (?-imsx:^<\/script>\s+-->) matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- < '<' ---------------------------------------------------------------------- \/ '/' ---------------------------------------------------------------------- script> 'script>' ---------------------------------------------------------------------- \s+ whitespace (\n, \r, \t, \f, and " ") (1 or more times (matching the most amount possible)) ---------------------------------------------------------------------- --> '-->' ---------------------------------------------------------------------- ) end of grouping ----------------------------------------------------------------------

    ... then you'll note that the regular expression only matches at the beginning of the string. Maybe you want to change that expression (and maybe the others as well) to allow for optional whitespace between the beginning of the string and the </script> tag. You would then add \s* between the "beginning of the string" anchor and the match for </script>.