Hayest has asked for the wisdom of the Perl Monks concerning the following question:

Hello all, I'm having some issues with the output I'm getting with a simple word and character count program. I need to count the amount of words and the amount of characters from input.txt and print the count to output.txt. Everything is working, except my output is being produced for line by line in my .txt file. How can I get the program to return one word count and one character count for the whole .txt file?
use strict; use warnings; open(my $in, "<", "input.txt") or die "Cannot open < input.txt: $!"; open(my $out, ">", "output.txt") or die "Cannot open < output.txt: $!" +; my ($words, $chars) = (0, 0); while (<$in>) { $chars += length($_); $words += scalar(split(/\s+/, $_)); print $out ("Words=$words\nCharacters=$chars\n"); }
The input.txt file has 3 lines to it, which is why I think Words and Characters is outputting 3 times. This is the output I am getting:
Words=10 Characters=68 Words=81 Characters=475 Words=116 Characters=684

Replies are listed 'Best First'.
Re: Output from read/write txt file
by toolic (Bishop) on Mar 12, 2015 at 15:25 UTC
    Move the print outside of the loop:
    use strict; use warnings; open(my $in, "<", "input.txt") or die "Cannot open < input.txt: $!"; open(my $out, ">", "output.txt") or die "Cannot open < output.txt: $!" +; my ($words, $chars) = (0, 0); while (<$in>) { $chars += length($_); $words += scalar(split(/\s+/, $_)); } print $out ("Words=$words\nCharacters=$chars\n");

    You might want to chomp if to exclude the newline from the character count.

      It needs to be outside of the loop because of the way I read input into the program and it's looping through line by line? Or if not, can you explain why it needs to be outside of the loop? Thanks!
        It needs to be outside of the loop because of the way I read input into the program and it's looping through line by line?
        Yes.

        If you have any further questions, post a small sample of your input file and the exact output you desire.

        Yes. It needs to be outside the loop because your loop's going through the input file line by line. Everything that's inside the loop is done for each individual line, so if you print to your output file inside the loop, you'll print to it for every single individual line of your input file.

        Move the print statement out of the loop, and it'll only execute once, after the loop is done and the entire input file has been read and processed.