Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do your Rewind File Handles? 1

Status
Not open for further replies.

bryantg

Technical User
Dec 22, 2001
9
BE
Hello All,
I am attempting to read two files, I want to compare file1 against file2 then output only the lines that are not found in file1 to out.file

I know how to open the file handles and output to the file handle, but the process only reads the file1 one time.



Is there a way to read each line of FILE1 theN read the complete FILE2 and print each line from FILE2 that is not found in FILE1?

Help and thanks....




 
Bryan,

If file1 is small enough to read into memory you could do something like this.
[tt]
# read all of file1
open(F,"file1")||die;
while(<F>){
$file1hash{$_}=1; # into a hash array
}
close(F);

# create the output file
open(OF,&quot;out.file&quot;)||die;
# then read through file2
open(F,&quot;file2&quot;)||die;
while(<F>){
print OF $_ unless defined($file1hash{$_});
}
close(F);
[/tt]

Mike
michael.j.lacey@ntlworld.com
Email welcome if you're in a hurry or something -- but post in tek-tips as well please, and I will post my reply here as well.
 
Mike.................................Thanks A BUNCH!!! It worked like a champ.

but i have a question if i wanted to view what was contained in the hash array how would i print it out???

THANKS AND HAPPY HOLIDAYS!!
 
thanks :)

This prints a sorted list of keys and the associated values in the file1hash:

foreach $key (sort(keys %file1hash)) {
print $key, '=', $file1hash{$key}, &quot;\n&quot;;
}

That's the usual way you would use this - but you only have a 1 in each value, so you could just say:

foreach $key (sort(keys %file1hash)) {
print &quot;$key\n;
}


Happy holidays,

Mike
michael.j.lacey@ntlworld.com
Email welcome if you're in a hurry or something -- but post in tek-tips as well please, and I will post my reply here as well.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top