vivek
vivek

Reputation: 3

open files sequentially and search for content match in perl

I am new to perl.

I am comfortable with opening two files and checking their contents, but how do I open files one after another in a loop and check their contents?

Upvotes: 0

Views: 91

Answers (2)

yoniyes
yoniyes

Reputation: 1020

In addition to Chankey Pathak's answer, if you want to iterate over files in some directory (meaning you don't know what are the names of the files you want to process, but you know their location), the File::Find module is an easy and straightforward solution.

Upvotes: 0

Chankey Pathak
Chankey Pathak

Reputation: 21666

As mkHun suggested, you can use an array to store filenames then loop over it. See the below template to get an idea:

#!/usr/bin/perl
use strict;
use warnings;
my @files = qw(file.txt file2.txt file3.txt filen.txt);
foreach my $file (@files){
    #open file in read mode to check contents
    open (my $fh, "<", $file) or die "Couldn't open file $!";
    #loop over file's content line by line
    while(<$fh>){
        #$_ contains each line of file. You can manipulate $_ below
        if($_ =~ /cat/){
            print "Line $. contains cat";   
        };
    }
    close $fh;
}

Also read:

Upvotes: 2

Related Questions