in reply to Output from read/write txt file

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.

Replies are listed 'Best First'.
Re^2: Output from read/write txt file
by Hayest (Acolyte) on Mar 12, 2015 at 15:29 UTC
    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.

        Once I put my print statement outside of the loops I am getting the output I desire. Thanks again!

      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.