Megiddo Megiddo - 3 months ago 12
Perl Question

how to extract titles from a text file and use those titles to open other files and search for patterns

I am trying to figure out a Perl program that reads a text file containing file names, opens each of those files and searches them for a regular expression.

I am reasoning that first I need to read the file and save everything into an array.

Then

foreach
element of the array,
open
the corresponding file and search within it.

There seem to be too many loops and I can`t keep track. Can someone please help?

Answer

My approach would be like below to solve the problem.

my $filename = 'names.txt';
open (my $fh, "<", $filename) or die $!;

# assuming each line contains file name
while ( <$fh> ) {
    chomp $_;
    my $file_contents;
    {
        open (my $fh, '<', $_) or die $!;
        local $/ = undef;
        $file_contents = <$fh>;
        close $fh;
    }
    print "Matched!" if $file_contents =~ /GGGGG/;
}

See: