tulians tulians - 1 month ago 5x
Perl Question

Perl file I/O issue

I'm developing a Perl script that's supposed to generate an HTML file from numerical values from other file. The idea is to read the file that has these values and then list them in a separate HTML file. The file that contains the numerical values is updated every a certain period of time, and those changes should be seen on the HTML.

Even though these values are correctly read (I've tested it) they are not printed in the HTML. Whats-more, the HTML tags are not even printed. This is the code I've written:

use IO::Handle;
use CGI qw(:standard);

print "Status: 200 OK", "\n";
print "Content-type: text/plain", "\n\n";

for(;;) {
open (my $input_file, "<", "/path/to/input/file/input_file.txt") || die "Unable to open the file: $!";
open (my $html_file, ">", "/path/to/html/file/index.html") || die "Unable to open the HTML file: $!";
print $html_file "<html><head><title>title</title><META HTTP-QUIV='refresh' CONTENT='10'></head><body>";
@lines = <$input_file>;
foreach my $line (@lines) {
print $html_file "<p>$line</p>";
print $html_file "</body></html>";
sleep 1;
close $input_file || die;
close $html_file || die;

The script only works in the first for iteration. What I mean is that the HTML tags and the numerical values are correctly printed in the output file. Then, from iteration 2 to N, the file remains literally empty. I can not see what I'm missing here. Why does it work in the first iteration but not in the following ones?

Thanks in advanced.


You need to close the file before the sleep. As it stands, the data is flushed to the file by the close and then immediately overwritten by the next open, and left empty for one second

You also need to write

close $html_file or die $!

as the code you have is equivalent to

close($html_file || die)

so your program will never die as long as $html_file is true