Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://506995]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (14)
As of 2017-07-25 13:20 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (370 votes). Check out past polls.