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

Hi,

How can i make this CODE print just like terminal does ??

#!/usr/bin/perl -w use strict; print "Content-type: text/html\n\n"; my $i = 0; while($i < 10){ print "$i\n"; sleep(5); $i++; }

in the terminal it will print a number every 5 seconds .. but in the browser it will wait till the time ends then print all the numbers in the same time

Any help? Thanks so much.

Replies are listed 'Best First'.
Re: Printing Like Terminal Does
by halley (Prior) on Sep 15, 2005 at 14:26 UTC
    This is really not how HTTP works. Even if you auto-flush your output from your CGI program, any number of things may get buffered at other points in the network or client.

    You should look at JavaScript or other "dynamic web page" mechanisms which get the client to help this task render as desired.

    --
    [ e d @ h a l l e y . c c ]

Re: Printing Like Terminal Does
by Roy Johnson (Monsignor) on Sep 15, 2005 at 14:42 UTC
    You'll have to do it as a series of pages, each of which autoloads the next.

    Caution: Contents may have been coded under pressure.
      My question is about the same... Show information before end of script Problem if you do a serie of pages, is that assuming you have a first "please wait" page calling a second one, longer to execute, it will show a white page until this second one executes. Andrei

      Edit: g0n - Turned 'http' link into monklink.

        You would have two things going on: a long-running process that does not communicate with the browser, and an auto-updating process spawned by the long-running one.

        The long-running process would write a status file periodically, and the fast-updating page would check that status file and relay the information to the browser, reloading regularly. When the status file indicate the process was done, then the relaying process would send the final results in a page that doesn't auto-reload.


        Caution: Contents may have been coded under pressure.
Re: Printing Like Terminal Does
by PreferredUserName (Pilgrim) on Sep 15, 2005 at 15:13 UTC
    I don't think you really want to do what you think you want to do, but here it is:

    #!/usr/bin/perl -w use strict; use CGI qw(:all); my $url = url(); my $high = defined(param('high')) ? param('high') + 1 : 0; my $timeout = 1; my %refresh_directive = $high >= 9 ? () : (-head => meta({ -http_equiv => 'refresh', -content => "$timeout;url=$url?high=$hi +gh"})); print header(), start_html(%refresh_directive); for (0 .. $high) { print "$_<br>\n"; } print end_html();
Re: Printing Like Terminal Does
by ChrisR (Hermit) on Sep 15, 2005 at 14:13 UTC
    $| = 1; Will turn on the autoflush