Cicatrix has asked for the wisdom of the Perl Monks concerning the following question:

I have two files with different data. one is a Data file and the other temp file. I need to compare the the temp file with Data file and only if the temp file has entries matching Data file, i have to filter out the rest of the data in temp file and making it more specific !! can you please guide me ??

Replies are listed 'Best First'.
Re: File Compare
by Nikhil Jain (Monk) on Mar 23, 2011 at 05:02 UTC

    1. see File::Compare - Compare files or filehandles

    2. Or you can try something like,
    my %data_hash; open(my $fh, '<', "datafile.txt") or die $!; while(<$fh>){ $data_hash{$_} = 1; } close($fh); open(my $fh1, '<', "tmpfile.txt") or die $!; while(<fh1>){ if(defined($data_hash{$_})){ print"Line match"; }else{ print"Line not match"; } } close($fh2); close($fh1);
      hi nikhil. thanks for that snippet!! thats working fine, but i'm want to print the matched pattern into another file. not just saying its a match. how can u do that?? please help !!
Re: File Compare
by Nikhil Jain (Monk) on Mar 23, 2011 at 07:34 UTC

    Hi Cicatrix, see my updated answer below.

    my %data_hash; open(my $fh, '<', "datafile.txt") or die $!; while(<$fh>){ $data_hash{$_} = 1; } close($fh); open(my $fh1, '<', "tmpfile.txt") or die $!; while(<fh1>){ if(defined($data_hash{$_})){ print"Line match"; #open new file in write mode and print line on file open(my $fh2, '>', "newfile.txt") or die $!; print $fh2 $data_hash{$_}; }else{ print"Line not match"; } } close($fh2); close($fh1);

      Hi Nikhil. I tried with this below snippet but this is not getting into the if loop at all.

      open(TMPL, '<', "HTML.txt") or die $!; %dump = $resp->content; print TMPL %dump; while (<TMPL>) { $dump{$_} = $_; } close(TMPL); open FILE, "> new_HTML.txt" or die $!; open FILE2, "< Users.txt" or die $!; while(<FILE2>) { if(defined($sp_dump{$_})) { print FILE $sp_dump{$_}; } else { print"Line not match"; } } close(FILE2); close(FILE);

      Here * HTML.txt is the text file with HTML content from a URL * Users.txt contains some users data * new_HTML.txt is where i need only User specific data (from Users.txt) in the same format as HTML.txt I need the whole content in new_HTML.txt to be as it is in HTML.txt BUT only for those Users in the Users.txt Am doing the right stuff here?