如果您正在剝離「嵌套」的意見,即:
/* This is a comment
/* that has been re-commented */ possibly /* due to */
various modifications */
正則表達式可能不是最好的解決辦法。特別是如果這樣跨越多行,如上面的例子。
上次我不得不做這樣的事情,我一次只讀一行,保留「/ *」級別(或者特定語言的任何分隔符)並且不打印任何東西除非計數爲0
這是一個例子 - 我提前道歉,因爲這是非常糟糕的Perl,但是,至少這應該給你一個想法:
use strict;
my $infile = $ARGV[0]; # File name
# Slurp up input file in an array
open (FH, "< $infile") or die "Opening: $infile";
my @INPUT_ARRAY = <FH>;
my @ARRAY;
my ($i,$j);
my $line;
# Removes all kind of comments (single-line, multi-line, nested).
# Further parsing will be carried on the stripped lines (in @ARRAY) but
# the error messaging routine will reference the original @INPUT_ARRAY
# so line fragments may contain comments.
my $commentLevel = 0;
for ($i=0; $i < @INPUT_ARRAY; $i++)
{
my @explodedLine = split(//,$INPUT_ARRAY[$i]);
my $resultLine ="";
for ($j=0; $j < @explodedLine; $j++)
{
if ($commentLevel > 0)
{
$resultLine .= " ";
}
if ($explodedLine[$j] eq "/" && $explodedLine[($j+1)] eq "*")
{
$commentLevel++;
next;
}
if ($explodedLine[$j] eq "*" && $explodedLine[($j+1)] eq "/")
{
$commentLevel--;
$j++;
next;
}
if (($commentLevel == 0) || ($explodedLine[$j] eq "\n"))
{
$resultLine .= $explodedLine[$j];
}
}
$ARRAY[$i]=join(" ",$resultLine);
}
close(FH) or die "Closing: $!";
也見http://stackoverflow.com/questions/2578671/where-can-i-find-information-about-perls-special-變量 – 2010-04-14 15:27:15