Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Ovid (2709)

  (email not shown publicly)
AOL IM: ovidperl (Add Buddy, Send Message)

Stuff with the Perl Foundation. A couple of patches in the Perl core. A few CPAN modules. That about sums it up.

Journal of Ovid (2709)

Saturday August 02, 2003
12:58 PM

Counting Lines of Code

[ #13861 ]

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;

        wanted     => \&count_lines,
        preprocess => \&extensions,

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 = <FILE>)) {
        chomp $line;
        next if $line =~ /^\s*#/ || $line =~ /^\s*$/;

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

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • 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...

  • 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 :)