in reply to Tricky regexp
Knock those out of your @files before trying to open anything. (see http://perldoc.perl.org/perlfunc.html)
You have some other problems in this script. Pay special attention to graff's discussion of path. Some will be easily solved if you add use diagnostics; to your pragmata; some are in nature of your failure to test the open at line 21 (and -- in the same line -- failure to use what's now considered best practice: 3 arg open with lexical filehandles.)
Perhaps most critical among the problems you didn't ask about is the attempt at line 23 to test an array (in scalar context) for a match -- and you need to read about qr/.../ -- either qr or in Quote and Quote-like Operators to make your regex match what you expect... and at line 24, where you'll find you're pushing something quite unexpected onto @found.
Updated for grammar, markup and clarity
Update 2 (Warning: Sunday morning content): This is one way of attacking your target (and problem) that's along the lines you initially tried:
#!/usr/bin/perl use warnings; use strict; # use diagnostics; #regexp.pl # 911425 print "Enter the full path to the directory you want to search: "; my $folder = <>; chomp $folder; chdir($folder); opendir(DIR, $folder) or die "Can't open $folder, $!"; my @files = readdir(DIR) or die "Can't readdir $folder, $!"; print "What's the phrase you're looking for?: "; my $find = <STDIN>; chomp $find; my $searchterm = qr/$find/; my (%found, $found, $file); for $file(@files) { next if ($file =~ /^\./); next unless (-T $file); # text files only (excludes binary f +iles such as *.doc or .xls) open(my $fh, '<', $file) or die "Can't open $file: $!"; my @content = <$fh>; for my $line(@content) { if ($line =~ /$searchterm/i) { my $key = $file; $found{$key} += 1; } } } while (my ($key, $value) = each %found) { print "$key has \t $value instance(s) of \t \"$find\"\n"; }
|
|---|