|
发表于 2004-4-29 12:58:55
|
显示全部楼层
修改了一下
确实是存在单行/* */会出错的问题,我前面没发现是因为所使用的测试文件没选好。
修改后的代码如下:
-
- #!/usr/bin/perl -w
- #To count the lines for c/c++ header/source files, omitting comments, empty line, and joining the lines seperated by '\'.
- use strict;
- my $total = 0;
- foreach my $src(@ARGV){
- # print "to count file $src\n";
- my $lines = &countline($src);
- $total += $lines;
- print "\t$lines : $src\n";
- }
- print "\t$total : total\n";
- sub countline{
- my $src = $_[0];
- my $count = 0;
- open(SRC, "<$src") or die("Can't open file $src for reading due to: $!\n");
- READLINE:
- while(<SRC>){
- if($_ =~ /\\$/){ #line to be continued
- $_ .= <SRC>;
- redo READLINE;
- }elsif($_ =~ /^\s*\/\*.*\*\/(.*)$/){ #single line comments, which may be followed by a statement/comments.
- $_ = $1;
- redo READLINE;
- }elsif(($_ =~ /^\s*\/\//)# // comments
- || ($_ =~ /^\s*$/) # empty line
- ){
- next;
- }elsif($_ =~ /^\s*\/\*/){ #multi-line comments begins
- while(my $next = <SRC>){
- if($next =~ /.*\*\/(.*)/){ #comments may be followed by a statement which should be counted.
- $_ = $1;
- redo READLINE; #$_ may be comments too.
- }
- }
- }else{
- # print "Counted line $count : $_\n";
- $count++;
- }
- }
- close(SRC);
- return $count;
- }
复制代码
所选用的测试文件为:
- /*
- * =====================================================================================
- *
- * Filename: test.cpp
- *
- * Description: test clines.pl
- *
- * Version: 1.0
- * Created: 04/28/04 14:19:51 CST
- * Revision: none
- * Compiler: gcc
- *
- * Author: Shixin Zeng (pupilzeng), [email]shixinzeng@sjtu.edu.cn[/email]
- * Company: Shanghai Jiaotong University
- *
- * =====================================================================================
- */
- #include <iostream>
- using namespace std;
- int
- main()
- {
- /* pure comments line */
- int j = 0;
- // pure comments lines.
- /* comments followed by a statement */ int i = 0;
- /* multi line comments
- * followed by a statement
- */ int j = 0;
- char * str = "this is a very long\
- line";
- /* comments followed by comments */ /*comments */
- cout<< "hello, world\n";
- /* multi-line comments
- * fllowed by multi-line coments */ /* another
- * multi-line comments*/
- return 0;
- }
复制代码
运行结果:
[php]
12 : test.cpp
12 : total
[/PHP] |
|