in reply to text search in a file
Here's an example:
#!/usr/bin/perl use warnings; use strict; use File::Find; use FileHandle; # Pattern is first argument; # remaining arguments are file or directory names. # Default directory is '.' my $pat = shift; my @results; # Do the search find(patternfinder(qr/$pat/,\@results), @ARGV?@ARGV:'.'); # Print the results print join("\n",@results),"\n"; sub patternfinder { # Generate a sub to search for a pattern and save the results my($pattern,$result) = @_; # Anonymous sub in a closure return sub { my $fh = new FileHandle $_, "r" or return warn "Couldn't open '$File::Find::name': $!\n"; # Search for pattern, and add to array if it matches. while (<$fh>) { if (/$pattern/) { push(@$result,$File::Find::name); return; } } close($fh) or return warn "Couldn't close '$File::Find::name': $!\n"; } }
|
|---|