1 #!/usr/bin/perl
 2 # Script by Michael Howe <michael.howe@worc.ox.ac.uk> to count the number of
 3 # lines of code and comments in files.
 4 # Usage: linecount <file1> <file2> ... <fileN>
 5 # $Id: linecount 345 2010-07-04 18:08:57Z michael@MICHAELHOWE.ORG $
 6 use strict;
 7 use warnings;
 8 use Getopt::Long;
 9 
10 my $count = 0;
11 my $lines = 0;
12 my $comment = 0;
13 my $blank = 0;
14 my $ispod = 0;
15 my $files = 0;
16 my $lang = 'perl';
17 my $help = 0;
18 
19 my $result = GetOptions("l|lang=s" => \$lang,
20                         "h|help" => \$help );
21 
22 if( $help ){
23     print "Usage: $0 [--lang PHP] <file1> [<file2>...<fileN>]
24 
25     Counts number of lines in file(s), and analyzes as code/whitespace/comment.
26 ";
27     exit 0;
28 }
29 
30 my $normalcomment;
31 my $startpod;
32 my $endpod;
33 my $blankrx;
34 if( $lang eq 'PHP' ){
35     $normalcomment = qr{^\s*(?:#[^!]|//)}o;
36     $startpod = qr{^\s*/\*}o;
37     $endpod = qr{\*/}o;
38 } else {
39     $normalcomment = qr{^\s*#[^!]}o;
40     $startpod = qr{^=.*$}o;
41     $endpod = qr{^=cut$}o;
42 }
43 # Empty line:
44 $blankrx = qr{^\s*$}o;
45 
46 foreach ( @ARGV ) {
47 	open( FH, "<", $_ ) or warn "Can't open $_: $!" and next;
48 	while ( <FH> ) {
49 		chomp;
50 		if ( $ispod ) {
51 			$comment++;
52 			if ( m{$endpod}o ) {
53 				$ispod = 0;
54 			}
55 		} elsif ( m{$startpod} ) {
56 			$ispod = 1;
57 			$comment++;
58 		} elsif ( m{$normalcomment} ) {
59 			$comment++;
60 		} elsif ( m{$blankrx} ) {
61 			$blank++;
62 		} 
63 		$lines++;
64 	}
65 	$ispod = 0;
66 	close FH;
67 	$files++;
68 }
69 
70 my $codelines = $lines - $comment - $blank;
71 my $codepercent =  ( $codelines / $lines ) * 100;
72 my $blankpercent = ( $blank / $lines ) * 100;
73 my $commentpercent = ( $comment / $lines ) * 100;
74 print "Using language: $lang\n";
75 printf( "Files: %d\nLines: %d\nComments: %d (%.1f%%)\nBlank: %d (%.1f%%)\nCode: %d (%.1f%%)\n", $files, $lines, $comment, $commentpercent, $blank, $blankpercent, $codelines, $codepercent );


syntax highlighted by Code2HTML, v. 0.9.1