I'm not sure how to do this. So, I'm posting a new solution. The code I posted yesterday will eat comments from within a verbatim environment.
Here's a new example file to be cleaned:
I've a LaTeX source.
I'm ready %for submission
%But first I would like
to strip its comments.
So I hope there are
100\% auto
ways to get this done.
\begin{comment}
Because there are subtle ways to mess it up.
\end{comment}
\begin{verbatim}
next two lines should not be lost
% don't lose this line
% this line should stay too
\end{verbatim}
According to the verbatim package documentation verbatim and comment environments should not be nested. The following code (similar to what I posted yesterday) will not eat commented lines that appear within a verbatim environment.
Here is the corrected Perl code:
#!/usr/bin/perl
use strict 'vars';
&MAIN(@ARGV);
sub MAIN {
my ($filehandle) = @_;
open FILE, "<$filehandle";
my @doc = <FILE>;
close FILE;
&removeComments(\@doc);
foreach my $line ( @doc ){
print $line;
}
return 1;
}
sub removeComments {
my ($docarray) = @_;
my $isCommentEnvironment = "no";
my $isVerbatimEnvironment = "no";
my @newdoc;
foreach my $line ( @{$docarray} ){
$isVerbatimEnvironment = "yes" if ( $line =~ /^\\begin{verbatim}/ );
$isCommentEnvironment = "yes" if ( $line =~ /^\\begin{comment}/ );
if ( ($isVerbatimEnvironment eq "no") && ($isCommentEnvironment eq "no") ){
next if ($line =~ /^%/);
## Temporarily replace "%" that you want to keep with a dummy string
## that does not appear elsewhere in your document. Then, remove remainder
## of lines that still contain "%".
if ( $line =~ /\\%/){
$line =~ s/\\%/TMP::PERCENT/g;
$line =~ s/%.*//;
$line =~ s/TMP::PERCENT/\\%/g;
} else {
$line =~ s/%.*//;
}
push @newdoc, $line;
}
push @newdoc, $line if ( $isVerbatimEnvironment eq "yes" );
$isVerbatimEnvironment = "no" if ( $line =~ /^\\end{verbatim}/ );
$isCommentEnvironment = "no" if ( $line =~ /^\\end{comment}/ );
}
@{$docarray} = @newdoc;
return 1;
}
verbatimpackage. – Richard Nov 21 '12 at 12:29%blabla ..– Herbert Nov 21 '12 at 12:32