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

Hello! This works in cmd just fine
open(File, "file.txt"); while($text = <File>){ @words = split(' ', $text); for $word(@words){ print "$word\n"}};
I am trying to get it to print in a txt file, but can't figure out why something like the following is not working:
open(S, 'file.txt'); while($text = <S>){ @words = split(' ', $text); for $word(@words){ my $filename = 'report.txt'; open(my $fh, '>', $filename) or die "Could not open file '$filename' $ +!"; print $fh "$word\n"; close $fh; print "done\n"; }};
I still consider myself new to perl so there must be something I don't get. Thanks in advance.

Replies are listed 'Best First'.
Re: Script works fine in cmd but doesn't print to txt
by Fletch (Bishop) on Jul 12, 2019 at 18:30 UTC

    Your second open for the writing is clobbering the contents of your "report.txt" every time you go through the list of words so it's only going to contain the last word from the last line in "file.txt". You probably want to move that open outside the outer while loop (as well as adding error checking to opening "file.txt" for reading but that's another story).

    Edit: Additionally if you formatted things better it'd be clearer what your code is doing and you might could see where the problem is more easily.

    Edit again: Meh, fish.

    my $infile = q{file.txt}; my $outfile = q{report.txt}; open(my $in_fh, q{<}, $infile ) or die "Couldn't open '$infile' for r +eading: $!\n"; open(my $out_fh, q{>}, $outfile) or die "Couldn't open '$outfile' for +writing: $!\n"; while( <$in_fh> ){ chomp; my @words = split( q{ } ); for my $word (@words) { print $out_fh "$word\n"; } } close( $in_fh ); close( $out_fh ); print "done\n";

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Script works fine in cmd but doesn't print to txt
by haukex (Archbishop) on Jul 12, 2019 at 20:15 UTC

    What's going wrong is that the open mode > clobbers the output file. Although you could use >> to append to the file, opening it on every iteration of the loop is pretty inefficient, and so Fletch's suggestion of moving the open outside of the loop is better.

    You should also definitely always Use strict and warnings, and apply the advice from "open" Best Practices to all of your opens.