All pastes #1567227 Raw Edit

findwords.pl

public text v1 · immutable
#1567227 ·published 2009-09-15 16:36 UTC
rendered paste body
#!/usr/bin/env perl
use strict;
use warnings;

# Search files in directory and all subdirectories.
sub list_files {
	my $dir = shift @_;

	opendir my($dh), $dir
		or die "Cannot open directory '$dir': $!";
	my @dir = map { "$dir/$_" } grep { !/^\.\.?$/ } readdir $dh;
	closedir($dh);
	
	my @files;
	my @dirs = grep { -d "$dir/$_" } @dir;
	push @files, grep { -f "$dir/$_" } @dir;
	push @files, list_files($_) for @dirs;
	
	return @files;
}

# Return usage
sub usage {
	"Usage: ./findwords.pl <dir> <word pattern>\n";
}

die usage unless defined @ARGV;
die usage unless scalar @ARGV == 2;

my %matches;
for my $file (list_files $ARGV[0]) {
	open FILE, $file
		or print STDERR "Cannot not open file '$file': $!";
	while (<FILE>) {
		my @m = m/\W($ARGV[1])\W/;
		$matches{$_} = 1 for @m;
	}
}

print "$_\n" for keys %matches;
print "\n------------------\nSum: ", scalar keys %matches, "\n";