Counting Lines of Code

Ovid on 2003-08-02T17:58:59

I was curious how many lines of code I had written for a project. Admittedly that's a dicey question, but a rough answer was sufficient for me. I skipped blank lines and anything beginning with a hash mark. Everything else, including POD, was counted. It's just a quick hack, really.

#!/usr/bin/perl -w
use strict;
use File::Find;

my ($TOTAL,$LENGTH,%LINES) = (0,0);
my %EXTENSIONS = map { $_ => 1 } qw( .pl .pm .t .cgi );

my @folders =  @ARGV;
@folders    = '.' unless @folders;

find(
    {
        wanted     => \&count_lines,
        preprocess => \&extensions,
    },
    @folders
);

foreach my $file ( sort keys %LINES ) {
    printf "%${LENGTH}s: %d\n", $file, $LINES{$file};
}
printf "%${LENGTH}s- ----\n", '-' x $LENGTH;
printf "%${LENGTH}s: %s\n", 'Total', $TOTAL;

sub count_lines {
    return if -d;
    $LENGTH = length if length > $LENGTH;
    my $file = $_;
    open FILE, '<', $file or die "Cannot open ($file) for reading: $!";
    while (defined (my $line = )) {
        chomp $line;
        next if $line =~ /^\s*#/ || $line =~ /^\s*$/;
        $LINES{$_}++;
        $TOTAL++;
    }
}

sub extensions {grep {-d || exists $EXTENSIONS{substr($_, index $_, ".")}} @_}


lines skipped

phillup on 2003-08-02T20:07:04

I skipped blank lines and anything beginning with a hash mark.

Might I suggest that, to some, the lines beginning with a hash mark are every bit as important as those that don't?

Just something to think about...

Counting lines

dws on 2003-08-02T20:38:22

If you want the count to be the same for $baz++ if exists $foo{$bar};

as it is for

then you've got a bit more work to do. A handful of patterns to ignore should get you pretty close. (Aside from POD, that is :)

Re:Counting lines

dws on 2003-08-02T20:41:55

Aaargh. That should be
$baz++ if exists $foo{$bar};
vs.
if ( exists $foo{$bar} )
{
  $baz++;
}