Perl get browser to render HTML instantly while script runs

Simply copy this code into the top of your Perl script and enjoy. All print statements will go straight to users browser and render instantly.

$|++;
print "Content-type: text/html\r\n";
print "Content-Encoding: plain\r\n\r\n";
&load_buffer; 
sub load_buffer {
        my $cmd = qq{perl -e "\$|++; print ' ' and sleep(1) for 1..1"};
        open my $PROC, '-|', $cmd or die $!;
        while (sysread $PROC, $buffer, 1) { print " ", ' ' x 1000, "\n";}
}

The explanation

$|++; #This is needed to disable buffering
print “Content-type: text/html\r\n”;
# This header is a quick hack to deny browser to gzip/deflate your output
print “Content-Encoding: plain\r\n\r\n”;
&load_buffer; #keeps the browser window printing progress while script runs

sub load_buffer {
my $cmd = qq{perl -e “\$|++; print ‘ ‘ and sleep(1) for 1..1”};
open my $PROC, ‘-|’, $cmd or die $!;
while (sysread $PROC, $buffer, 1) { print ” “, ‘ ‘ x 1000, “\n”;}

}