#!/usr/bin/perl

# Search through files like grep, but ONLY if they're text files.
# 
# Usage: tgrep [-l] pattern [files]
# 
# Has only one option, -l, which causes it to list the files
# containing the pattern rather than the lines containing the pattern.
# 
# Origin unknown, but in July 2010 available from
# http://www.cpan.org/scripts/nutshell/ch6/tgrep

# Handle
if ($ARGV[0] eq '-l') {
    shift;
    $action = <<'EOF';
            print $file,"\n";
            next FILE;
EOF
}
else {
    $action = <<'EOF';
            print $file,":\t", $_;
EOF
}

# Get pattern and protect the delimiter we'll use.

$pat = shift;
$pat =~ s/!/\\!/g;

# Generate the program.

$prog = <<EOF;
FILE: foreach \$file (\@ARGV) {
    open(FILE,\$file) || do {
        print STDERR "Can't open \$file: \$!\\n";
        next;
    };
    next if -d \$file;    # ignore directories
    next if -B \$file;    # ignore binary files
    while (<FILE>) {
        if (m!$pat!i) {
            $action
        }
    }
}
EOF

# We often put in lines like this while developing scripts, so we
# can see what program the program is writing.

print $prog if $debugging;

# And finally, do it.

eval $prog;
die $@ if $@;
