Nandini143 Nandini143 - 5 months ago 8
Perl Question

Search for words ending with 'ing' from a text file in perl

I have a text file , lets call it file1.txt :

cats
and
dogs
are
running
around
|

john
loves
mary
|

I
am
swimming
|


I am trying to build a program which looks for the words ending with 'ing' and prints CC beside them on the same file or to a different output.txt file.

Desired Output

cats
and
dogs
are
running CC
around
|

john
loves
mary
|

I
am
swimming CC
|


I went through the available articles in the forum and tried building the following code ,however it gives me an arbitrary result with every word followed by " CC ".

#use warnings;
#use strict;

my $file = 'file1.txt';

open(my $word_fh,"file1.txt") or die "Couldn't open file file1.txt, $!";

my %word_match = map {chomp $_; $_ => 0} <$w_fh>;

close $w_fh;


open my $fh, '<', $file or die $!;

while (<$fh>){
chomp;

my @words_in_line = split;

for my $word (@words_in_line){

$word =~ /ing$/;
$word .= ' CC' if exists $words_match{$word};

print " $word\n";
}
}


The output that I get is this :

cats CC
and CC
dogs CC
are CC
running CC
around CC
| CC
john CC
loves CC
mary CC
| CC
I CC
am CC
swimming
| CC


I know I am doing something wrong. Any hints or suggestions would be appreciated. Thanks in advance !

Answer

That's because you are reading your file1.txt twice and check whether they match. In the while loop you print 'CC' if the current line of file1.txt is also contained somewhere in file1.txt. Since they are the same files this is always true and 'CC' is printed after every line.

You might have been inspired by this question where the OP wanted to check whether words in file A are also contained in file B. Yours is a different case because you don't have two files.

Drop the first reading of file1.txt into %word_match and iterate over the file just once. Your line $word =~ /ing$/; only checks whether $word ends in ing but throws the result away. That code is similar to

$i>5;
print "i is greater than 5\n";

You have to change that to

if ( $i>5 ) {
    print "i is greater than 5\n";
}

In summary this gives

#!/usr/bin/env perl

use strict;
use warnings;

open my $fh, '<', 'file1.txt' or die $!;
while (<$fh>){
    chomp;
    print $_;
    if ( /ing\s*$/ ) {
        print ' CC';
    }
    print "\n";
}
close($fh);