Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: how to comment the lines if found a match

by n3toy (Hermit)
on Dec 06, 2008 at 00:18 UTC ( [id://728440]=note: print w/replies, xml ) Need Help??


in reply to how to comment the lines if found a match

There are a few shortcuts that could make this smaller, but the code below is one way to comment lines that matched a list of words.

However, you will probably need to dial in the regex to better meet your needs.

#!/usr/bin/perl use strict; use warnings; my @file_a_array; my $newfile; my $file_a = <path to word file>; my $file_b = <path to lines of text>; open (FILE_A, "$file_a") or die "couldn't open the file!"; while (my $line = <FILE_A>) { chomp ($line); push (@file_a_array, $line); } close (FILE_A); open (FILE_B, "$file_b") or die "couldn't open the file!"; while (my $line = <FILE_B>) { chomp ($line); foreach my $word (@file_a_array) { if ($line =~ /$word/) { $newfile = $newfile . "# "; } } $newfile = $newfile . $line . "\n"; } close (FILE_B); open (FILE_B, ">$file_b") or die "couldn't open the file!"; print FILE_B $newfile; close (FILE_B); print "end\n";


Hope this helps!

Jamie

Replies are listed 'Best First'.
Re^2: how to comment the lines if found a match
by matrixmadhan (Beadle) on Dec 06, 2008 at 14:15 UTC
    Would you mind, if I suggest very small suggestion to your code?

    $! will give more information regarding the type of failure

    open (FILE_A, "$file_a") or die "couldn't open the file!"; >>open (FILE_A, "$file_a") or die "couldn't open the file $file_a <$!> +!";
    close function will also fail, its better to check that as well

    close (FILE_A); >>close (FILE_A) or die "Unable to close file";
      Thanks alot. This works exactly how I want. Thanks for all your support.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-25 10:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found