#!/usr/bin/perl -w
######################################################################
# findgrep.pl
######################################################################
# Perl Power! - Michael Schilli 1998
######################################################################

use File::Find;
use strict;
                                      # fetch command
my ($startdir, $pattern) = @ARGV;     # line parameters

# check command line parameters
(defined $startdir && defined $pattern) || usage();
(-d $startdir) || die "Cannot open directory $startdir";

# trigger traverse algorithm
File::Find::find(\&fc, $startdir);

#################################################################
sub fc {                              # callback function
    my $file = $_;                    # save file name

    return unless -f $file;           # no directories
    return unless -T _;               # text files only

                                      # text seach in file
    open(FILE, "<$file") || warn "Cannot open $file";
    while(<FILE>) {
        if(/$pattern/o) {             # match found?
                                      # output file and line
            print "$File::Find::dir/$file: $_";
        }
    }
    close(FILE);

    $_ = $file;                       # reset $_
}

#################################################################
sub usage {                           # message in case of incorrect
                                      # command line parameters
    $0 =~ s#.*/##g;                   # basename() for script path

    print "usage: $0 startdir pattern\n";
    exit 0;                           # program termination
}

