Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: comparing and deleting some words from file

by Roger (Parson)
on Nov 09, 2005 at 07:42 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-04-26 07:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found