Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: comparing and deleting some words from file

by Roger (Parson)
on Nov 09, 2005 at 07:42 UTC ( #506995=note: print w/ replies, xml ) Need Help??


in reply to comparing and deleting some words from file

Let me describe a quick way of doing this...

0. assumption - you will never modify file 1, because you will only delete from file 2;

1. read the first file into a hash table, having each word as the hash key;

2. create a third file;

3. while scanning the second file, check the hash table built in step 1 for existance of the word;
if the word exists, do not print to the third file;
if the word does not exist, print the the third file;

4. replace file 2 with the third file.

#!/usr/bin/perl -w use strict; use IO::File; my %hash = (); my $f = IO::File->new("file1.txt", "r") or die "can not open file 1"; while (my $line = <$f>) { chomp $line; for my $word (split /\s*,\s*/, $line) { $hash{$word}++; } } my $f3 = IO::File->new("file3.txt", "w") or die "can not create file 3 +"; my $f2 = IO::File->new("file2.txt", "r") or die "can not open file 2"; while (my $line = <$f2>) { chomp $line; my @words = (); for my $word (split /\s*,\s*/, $line) { if (! exists $hash{$word}) { push @words, $word; } print $f3 join(",", @words), "\n"; } undef $f; undef $f2; undef $f3; # then replace file 2 with file 3...


Comment on Re: comparing and deleting some words from file
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://506995]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (10)
As of 2015-07-03 11:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (51 votes), past polls