Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: compare two text files

by atcroft (Abbot)
on Jul 14, 2005 at 05:13 UTC ( #474751=note: print w/replies, xml ) Need Help??

in reply to compare two text files

First of all, while I don't know in this case if this is homework, the way your post is written sounds like some homework-like questions I have seen before. Most people here have already done their share of homework, and so may be a little reluctant to do someone else's as well. Show what you've tried so far, or even how you think you might, and you will likely get more/better results in the future. That having been said, now back to our regularly-scheduled post.

If the search list is short enough, you can store the items as keys in a hash, then loop thru general data file and push the line numbers into the hash when found, and when done list the entries found. Something like the following (untested) code might work...

open(SF, $searchfile) or die(qq{Can't open $searchfile for input: $!\n}); while (<SF>) { chomp; @{$results{$_}} = (); } close(SF); open(DF, $datafile) or die(qq{Can't open $datafile for input: $!\n}); while (<DF>) { foreach my $k (keys %results) { if (m/$k/) { push(@{$results{$k}}, $.); last; } } } close(DF); foreach my $k (sort keys %results) { if (scalar @{$results{$k}}) { printf "%s:\n\t%s\n", $k, join(",", sort @{$results{$k}}); } }

Hope that helps.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2023-01-31 10:25 GMT
Find Nodes?
    Voting Booth?

    No recent polls found