Hi,

I have 2 files. I need to read a line from the File 1 and check for it in File 2. If it is present, I need to delete that line from File 2.

File 1
A1
B1
C1

File 2
A1 ABCDEF
S1 EEE
C1 EFGH
D1 XYQ

Now, I need to read A1, go to file 2, search for it there and since it is present, I need to delete it from File 2.

Result of File 2 after the operation:
S1 EEE
D1 WXQ

It would have been wonderful if you show what you have tired. So that we can tell you where you are going wrong.

However, this will do:
Instead of writing the open function twice, I wrote just once in a subroutine. And used it to call and perform different operation on the files.

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

my $file1 = 'file1.txt';
my $file2 = 'file2.txt';

my %file_content;

open_read_file(    ## call the subroutine first time
    $file2,        ## use the file 2
    sub {          ## call an anynomous subroutine
        undef $file_content{ shift() };
    }
);

open_read_file(    ## call the subroutine first time
    $file1,        ## use the file 2
    sub {          ## call an anynomous subroutine
        my ($match) = @_;
        foreach my $value ( keys %file_content ) {
            if ( $value =~ m/$match/i ) {
                delete $file_content{$value};    ## delete matched key from hash
            }
        }
    }
);

print join "\n" => keys %file_content;

sub open_read_file {
    my ( $file, $code_ref ) = @_;
    open my $fh, '<', $file or die "can't open the file:$!";
    while (<$fh>) {
        chomp;
        $code_ref->($_);    ## the anynomous subroutine called in the subroutine

    }
}
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.