Dear all
I would like to read every file in a directory, if each file contains a line 'KAC 50' I will write to an output file. My code below write all the out output into only 1 file. How can I have many output files corresponding to the input files?

#!/usr/bin/perl
use strict;
use warnings;

my $outfile = "KAC.pdb";
open(my $fh, '>>', $outfile);

opendir (DIR, "/data/tmp") or die "$!";
my @files = readdir (DIR);
closedir DIR;

foreach my $file(@files){
open (FH, "/data/tmp/$file") or die "$!";
while (<FH>){
my($line) = $_;
chomp($line);
if ($line =~m/KAC 50/){
print $fh $_;
}
}
}
close FH;

Best regards
becon

I haven't tested this but something like the following should work. It opens a new file for output using a prefix plus the input file name for the name of each output file.

#!/usr/bin/perl
use strict;
use warnings;

#If you want to open a new output file for every input file
#Do it in your loop, not here.
#my $outfile = "KAC.pdb";
#open( my $fh, '>>', $outfile );

opendir( DIR, "/data/tmp" ) or die "$!";
my @files = readdir(DIR);
closedir DIR;

foreach my $file (@files) {
    open( FH, "/data/tmp/$file" ) or die "$!";
    my $outfile = "output_$file"; #Add a prefix (anything, doesn't have to say 'output')
    open(my $fh, '>', $outfile);
    while (<FH>) {
        my ($line) = $_;
        chomp($line);
        if ( $line =~ m/KAC 50/ ) {
            print $fh $_;
        }
    }
    close($fh);
}

Dear David Ellis
I got the solution. Thank you very much.
becon

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.