user5922864
user5922864

Reputation:

Perl script - Confusing error

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";

Upvotes: 0

Views: 75

Answers (1)

Castaglia
Castaglia

Reputation: 3089

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!

Upvotes: 2

Related Questions