Optimizing My PERL Script in 2026

I have a PERL script that counts the number of word in a directory. It is my daily journal word counter. I wrote it 10 years ago, and even then it was already ancient technology. Well, now in 2026, the directory has over 1.5 million words in it and it’s been bugging me that the count script is taking noticeably long and progressively getting worse.

I decided to give it to Claude and see what it would do. To my surprise, it fixed it.

My version was pretty basic

while (my $filename = readdir(DIR)) {
  push @files, $filename;
  open(FILE, "<$filename") or die "Could not open $filename: $!";
  while (<FILE>) {
    $wordcount += scalar(split(/\s+/, $_));
  }
}

Robot Overlord Version

When I asked Claude to optimize it, I was thinking it would start finding inefficiencies in the regex or the opening of file handles. Something along those longs.

To my delight, it did something completely reasonable. It counted all the words in each file and put that value in a hash along with the timestamp, and the saved that to the filesystem. The next the time script is run, loads all the word counts from the previous run. And it checks the timestamp of the filename and if it’s the same, it uses the saved count value. Making it quite efficient after the first run.

my $CACHE  = "$SOURCE/.wordcount_cache";
my $wordcount = 0;
for my $filename (@files) {
    my $mtime = (stat $filename)[9];
    my $entry = $cache->{$filename};

    if ($entry && $entry->{mtime} == $mtime) {
        $wordcount += $entry->{count};
        next;
    }

    my $count = 0;
    open(my $fh, '<', $filename) or do {
        warn "Skipping $filename: $!";
        next;
    };
    while (<$fh>) {
        $count += split ' ';
    }
    close($fh);

    $cache->{$filename} = { mtime => $mtime, count => $count };
    $wordcount += $count;
}

nstore($cache, $CACHE);

Claude has revived long lost projects for me

I like using Claude. So many little things or project ideas I’ve had over the years. It’s so easy to work on them now, and a joy.


Posted

in

by

Tags: