0

When I run this code, I am purely trying to get all the lines containing the word "that" in them. Sounds easy enough. But when I run it, I get a list of matches that contain the word "that" but only at the end of the line. I don't know why it's coming out like this and I have been going crazy trying to solve it. I am currently getting an output of 268 total matches, and the output I need is only 13. Please advise!

#!/usr/bin/perl -w
#Usage: conc.shift.pl textfile word

open (FH, "$ARGV[0]") || die "cannot open";
@array = (1,2,3,4,5);
$count = 0;
while($line = <FH>) {
    chomp $line;
    shift @array;
    push(@array, $line);
    $count++;
    if ($line =~ /that/)
    {
        $output = join(" ",@array);
        print "$output \n";
    }
}

print "Total matches: $count\n";
2
  • grep -c "that" file.txt? Commented Feb 13, 2016 at 18:37
  • By the way, your description of your problem is very confusing. You say that your problem is that your matches are only lines ending with your keyword "that". Then you say that you get 268 such lines, but you only need 13. Which is quite contradictory to your previous statement, and seemingly has nothing to do with what seems to be your real problem, which is the count variable which you print towards the end. You really should take a minute to formulate your question better. Commented Feb 13, 2016 at 18:41

1 Answer 1

2

Don't you want to increment your $count variable only if the line contains "that", i.e.:

if ($line =~ /that/) {
  $count++;

instead of incrementing the counter before checking if $line contains "that", as you have it:

$count++;
if ($line =~ /that/) {

Similarly, I suspect that your push() and join() calls, for stashing a matching line in @array, should also be within the if block, only executed if the line contains "that".

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.