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

I'm having a problem printing to stdout while receiving files over a socket connection. Below is part of the server code. Within the loop I push the file names into an array. I want to print out the array when it's done receiving, but if I put the print outside of the while loop, I get nothing. And if I put it in the loop, I get repeating values. Either I'm missing something real simple, or my server code needs some work. Thanks for your help.
while ($client = $server->accept()) { $receivefile = $receivepath . $timestamp . ".ORD"; push(@files, $receivefile); open FILE, $receivefile or die "Can't open: $!"; while (<$client>) { print FILE $_; } close FILE; $timestamp = $timestamp + 1; foreach $file (@files) { print "$file received"; } }

Replies are listed 'Best First'.
Re: Printing while receiving files from socket
by jryan (Vicar) on Oct 31, 2001 at 02:11 UTC

    You need to hot flush your output. Since you are using IO::Socket, you can do this by setting $client->autoflush(1) as soon as possible:

    while ($client = $server->accept()) { $client->autoflush(1);

    Also, you should use strict; and enable  -w (warnings). It will help you catch lots of mistakes and typos within your code.

Re: Printing while receiving files from socket
by ton (Friar) on Oct 31, 2001 at 01:06 UTC
    Don't know why you get nothing when you print outside the loop, but I can answer why you get repeating values within.

    With each iteration, you are pushing the newest file to the @files array, then printing out the contents of the entire array. So on the first iteration, you print out the first file, on the second you print out both the first and the second files, on the third you print out all three files, etc. Just print out $receivefile to get no repeats in your output.
    -----
    Be bloody, bold, and resolute; laugh to scorn
    The power of man...

Re: Printing while receiving files from socket
by slayven (Pilgrim) on Oct 31, 2001 at 00:55 UTC
    did you considered flushing $|? see perlvar for details