walking dirs recursively (I'm doing what on Fri nite?)

C. Abney cabney at cyberpass.net
Sat Apr 15 01:58:57 CDT 2000

Hmm, looking through the Cookbook, I notice File::Find is recommended
for recursive searches through a directory hierarchy.

Is there any reason why recursion down a directory hierarchy is best
left to this module?

To test using an array to store the directory names, I cobbled together
(a rewrite of) an 'rtgrep' I once did using bash (see below)

Seems to work, but am I missing something important (aside from the
weak command line flexibility -- it's just a quick mockup, for now)?

Einstein himself said that God doesn't roll dice. But he was wrong. And
in fact, anyone who has played role-playing games knows that God
probably had to roll quite a few dice to come up with a character like
Einstein.  -- Larry Wall                                     C. Abney

#! /usr/bin/perl -w
# Greps text files...
# Doesn't even try to follow links

use strict;

my ( $re, $path, @dirs, $dir );

$re = shift || die "Usage:\n\t$0 <regex> <dir or file>\n";
# this should just snarf the rest of the arg(s) up...
$path = shift || die "Usage:\n\t$0 <regex> <dir or file>\n";

if ( -d $path ) {
	push @dirs, $path;
} elsif ( -T $path ) {
	grepfile ( $path );
	exit 0;
} else {
	die	("Must be a text file or directory.\nUsage:\n",
		 "\t$0 <regex> <dir or file>\n" );

$re = qr/$re/;

foreach $dir ( @dirs ) { getfiles ( $dir ) };

sub getfiles
	my $d = shift;
	my ( @files, @textfiles );

	opendir DIR, $d;
	@files = grep { ! /^\./ } readdir (DIR);
	closedir DIR;

	foreach my $f ( @files )
		if ( -d "$d/$f" ) {
			push @dirs, "$d/$f";
		} elsif ( -T "$d/$f" ) {
			push @textfiles, "$d/$f";

	grepfile ( $_ ) for ( @textfiles );

sub grepfile
	my $file = shift;
	my $line_no = 0;

	open FILE, $file
		or die "Couldn't open file $file: $!";
	while (<FILE>)
		print "$file, $line_no: $_" if ( $_ =~ m/$re/ );
	close FILE
		or die "Couldn't close file $file: $!";


The posting address is: san-diego-pm-list at hfb.pm.org

List requests should be sent to: majordomo at hfb.pm.org

If you ever want to remove yourself from this mailing list,
you can send mail to <majordomo at happyfunball.pm.org> with the following
command in the body of your email message:

    unsubscribe san-diego-pm-list

If you ever need to get in contact with the owner of the list,
(if you have trouble unsubscribing, or have questions about the
list itself) send email to <owner-san-diego-pm-list at happyfunball.pm.org> .
This is the general rule for most mailing lists when you need
to contact a human.

More information about the San-Diego-pm mailing list