[D]利用perl进行文本替换

wu0792 2012-04-10 09:40:39
我想把某个目录下面的所有文件中前面的注释行删除掉,例如

/*
File Generated by NetTiers templates [www.nettiers.com]
Generated on : 2012年4月10日星期二
Important: Do not modify this file. Edit the file OracleDocPaperDocEquipProvider.cs instead.
*/

#region using directives
...

希望#region前面的内容删除,我试着写了代码,可发现文本被清空了,下面是我的代码

$dir='d:/g/r'; #查询的目录范围
opendir DIR,$dir or die "$!";

while($name = readdir DIR){
open FILE,">".$dir."\\".$name;
$lines = join '',<FILE>;

$lines =~ s/\/\*.*\*\///gs;
select FILE;
print $lines;

close FILE;
}

closedir DIR;
希望大家帮我看看,谢了!
--------
Double行动:
原帖分数:20
加分:20
...全文
228 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Crafter 2012-04-17
  • 打赏
  • 举报
回复
1楼说得对哈;不能用贪婪匹配;重新写过:

if ( $filecontent =~ s{
/
  • #the start /*
    .*? #the characters in the comment,
  • here must used non-greedy quantifiers ?
  • / #the end */
    \s* #the spaces between the comment and the next statement
    }{}sx
  • ) #x ignore the comments and spaces in the pattern, s make . includes newline
    {
    print "\n-------------------------\n";
    print $filecontent;
    print "\n-------------------------\n";
    }
Crafter 2012-04-17
  • 打赏
  • 举报
回复
暂且认为读写文件都正确,你需要的操作可能如下,我已经添加了注释,供参考,希望有用:


my $filecontent;
# read the file content to $filecontent
if ( $filecontent =~ s{
/
  • #the start /*
    .* #the characters in the comment
  • / #the end */
    \s* #the spaces between the comment and the next statement
    }{}sx
  • ) #x ignore the comments and spaces in the pattern, s make . includes newline
    {
    print "\n-------------------------\n";
    print $filecontent;
    print "\n-------------------------\n";
    }
    #output $filecontent to the file

nucgpeak 2012-04-16
  • 打赏
  • 举报
回复
\/\*(.*\n)*?\*\/

perl中支持多行匹配,用上面这个正则表达式试一下
song84217 2012-04-16
  • 打赏
  • 举报
回复
2楼正解
open FILE,">".$dir."\\".$name;
$lines = join '',<FILE>;
这里没有读出文件的内容。

应改成
open FILE,"<".$dir."\\".$name;

写入的时候要重新打开一个写的文件句柄
open FILE,">".$dir."\\".$name;
proorck6 2012-04-14
  • 打赏
  • 举报
回复
看不懂,帮顶,不过Perl的调试技巧也很重要。
I_NBFA 2012-04-11
  • 打赏
  • 举报
回复
open FILE,">".$dir."\\".$name;
你是写文件,根本没读出来东西。
jiuchang 2012-04-10
  • 打赏
  • 举报
回复
不要用贪婪匹配
$lines =~ s/\/\*.*?\*\///gs;

37,741

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧