CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [ewh006] File Comparison (2 files): Matching Occurences: Edit Log



Zhris
Enthusiast

Feb 25, 2018, 8:30 PM


Views: 9304
Re: [ewh006] File Comparison (2 files): Matching Occurences

Hi,

This sounds like a homework question, apologies if it isn't.

- open the keywords file and read it into a hash.
- read each email file in the emails directory.
- open each email file and split it into individual words, or use a regular expression.
- test if each individual word exists in the keywords hash.
- print the result.

Here is an example, the approach I would take, but perhaps beyond the complexity you require due to its heavy use of Path::Tiny, map and grep. Use it as a basis.


Code
use strict; 
use warnings;
use Path::Tiny;
$| = 1;
$, = "\n";
$\ = "\n\n";

my $dirpath_root = path( $0 )->parent;
my $filepath_keywords = $dirpath_root->child( 'keywords.txt' );
my $dirpath_emails = $dirpath_root->child( 'emails' );

# convert lines from keywords file into hash.
my %keywords = map { $_ => 1 } $filepath_keywords->lines( { chomp => 1 } );

# iterate over each email file in emails directory.
for my $filepath_email ( $dirpath_emails->children( qr/\.txt$/ ) )
{
# read email file and push matching keywords into array.
my @matches = grep { exists $keywords{$_} } map { /(\w+)/g } $filepath_email->slurp;

# print email file and matching keywords.
print $filepath_email, @matches;
}


Regards,

Chris


(This post was edited by Zhris on Feb 25, 2018, 8:32 PM)


Edit Log:
Post edited by Zhris (Enthusiast) on Feb 25, 2018, 8:30 PM
Post edited by Zhris (Enthusiast) on Feb 25, 2018, 8:31 PM
Post edited by Zhris (Enthusiast) on Feb 25, 2018, 8:32 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives