I am using the File::Grep
module. I have following example:
#!/usr/bin/perl
use strict;
use warnings;
use File::Grep qw( fgrep fmap fdo );
my @matches = fgrep { 1.1.1 } glob "file.csv";
foreach my $str (@matches) {
print "$str\n";
}
But when I try to print $str
value it gives me HEX
value: GLOB(0xac2e78)
What's wrong with this code?
The documentation doesn't seem to be accurate, but judging from the source-code — http://cpansearch.perl.org/src/MNEYLON/File-Grep-0.02/Grep.pm — the list you get back from fgrep
contains one element per file. Each element is a hash of the form
{
filename => $filename,
count => $num_matches_in_that_file,
matches => {
$line_number => $line,
...
}
}
I think it would be simpler to skip fgrep
and its complicated return-value that has way more information than you want, in favor of fdo
, which lets you just iterate over all lines of a file and do what you want:
fdo { my ( $file, $pos, $line ) = @_;
print $line if $line =~ m/1\.1\.1/;
} 'file.csv';
(Note that I removed the glob
, by the way. There's not much point in writing glob "file.csv"
, since only one file can match that globstring.)
or even just dispense with this module and write:
{
open my $fh, '<', 'file.csv';
while (<$fh>) {
print if m/1\.1\.1/;
}
}
I assume you want to see all the lines in file.csv
that contain 1.1.1
?
The documentation for File::Grep
isn't up to date, but this program will put into @lines
all the matching lines from all the files (if there were more than one).
use strict;
use warnings;
use File::Grep qw/ fgrep /;
$File::Grep::SILENT = 0;
my @matches = fgrep { /1\.1\.1/ } 'file.csv';
my @lines = map {
my $matches = $_->{matches};
@{$matches}{ sort { $a <=> $b } keys %$matches};
} @matches;
print for @lines;
Update
The most Perlish way to do this is like so
use strict;
use warnings;
open my $fh, '<', 'file.csv' or die $!;
while (<$fh>) {
print if /1\.1\.1/;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.