#!/bin/env perl
# Counts the number of lines in each .txt file.
use 5.10.1;
use warnings;
use strict;
use File::Next;
my $start = shift or die;
use IO::Handle;
pipe(FINDER, COUNTER);
COUNTER->autoflush(1);
my $child_pid;
if ($child_pid = fork()) {
close COUNTER;
my $total = 0;
while ( my $file = <FINDER> ) {
my $n = 0;
chomp $file;
open( my $fh, '<', $file ) or die "Can't open $file: $!\n";
while ( <$fh> ) {
++$n;
}
close $fh;
printf "%5d: %s\n", $n, $file;
$total += $n;
}
waitpid $child_pid, 0;
say "$total lines of text in $start";
}
else {
die "cannot fork: $!" unless defined $child_pid;
close FINDER;
my $iter = File::Next::files( { descend_filter => sub { $_ ne '.git' }, file_filter => sub { /\.txt/ } }, $start );
while ( my $file = $iter->() ) {
say COUNTER $file;
}
warn "############ Child is done looking #############\n";
exit 0;
}