Grep(3pm) | User Contributed Perl Documentation | Grep(3pm) |
File::Grep - Find matches to a pattern in a series of files and
related
functions
use File::Grep qw( fgrep fmap fdo ); # Void context if ( fgrep { /$user/ } "/etc/passwd" ) { do_something(); } # Scalar context print "The index page was hit ", ( fgrep { /index\.html/ } glob "/var/log/httpd/access.log.*"), " times\n"; # Array context my @matches = fgrep { /index\.html } glob "/var/log/httpd/access.log.*"; print SUMMARY $_ foreach @matches; # Mapping my @lower = fmap { chomp; lc; } glob "/var/log/httpd/access.log.*"; # Foreach style.. my $count; fdo { $count++ } @filelist; print "Total lines: $count\n"; # More complex handling my @matchcount; fdo { my ( $file, $pos, $line ) = @_; $matchcount[$file]++ if ( $line =~ /keyword/ ); } @filelist;
File::Grep mimics the functionality of the grep function in perl, but applying it to files instead of a list. This is similar in nature to the UNIX grep command, but more powerful as the pattern can be any legal perl function.
The main functions provided by this module are:
When entering BLOCK, the $_ variable will be localized to the current line. In addition, you will be given the position in LIST of the current file, the line number in that file, and the line itself as arguments to this function. While you can change $_ if necessary, only the original value of the line will be added to the returned list. If you need to get the modified value, use fmap (described below).
The LIST can contain either scalars or filehandle (or filehandle-like objects). If the item is a scalar, it will be attempted to be opened and read in as normal. Otherwise it will be treated as a filehandle. Any errors resulting from IO may be reported to STDERR by setting the class variable, $File::Grep::SILENT to false; otherwise, no error indication is given.
In addition, if you need additional fine control, you can use the internal function _fgrep_process. This is called just like fgrep/fmap/fdo, as in "_fgrep_process BLOCK LIST" except that you can control when the fucntion 'short circuits' by the return value from BLOCK. If, after processing a line, the BLOCK returns a negative number, the entire process is aborted, closing any open filehandles that were opened by the function. If the return value is 0, the current file is aborted, closed if opened by the function and the next file is then searched. A positive return value will simply go on to the next line as appropriate.
"fgrep", "fmap", and "fdo" may be exported, but these are not set by default.
Michael K. Neylon, <mneylon-pm@masemware.com>
perl.
2023-01-22 | perl v5.36.0 |