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

As part of a program I've been writing, I have a subroutine that iterates through a given file, line by line. It does not begin operating until it receives an EOF, however. If I give it a normal file, it's not a problem, but when I pass it STDIN, I need to operate on the incoming lines before EOF. Any ideas?
sub send_file { $_ = shift; foreach(<$_>) { sleep $time; print; } return(0); }
send_file(\*FILE); works fine b/c EOF arrives immediately, but send_file(\*STDIN); won't begin until I close the input stream.

Replies are listed 'Best First'.
RE: Looping line-by-line through STDIN before EOF is received
by Boogman (Scribe) on Aug 22, 2000 at 01:58 UTC
    Use a while loop instead of a foreach loop. The foreach loop will wait until it has a whole array of the input, whereas a while loop will go line by line.
Re: Looping line-by-line through STDIN before EOF is received
by btrott (Parson) on Aug 22, 2000 at 01:58 UTC
    foreach puts the diamond op (<>) in a list context, which means that it reads until EOF, then splits it up into a list. You want it in scalar context:
    while (<$FH>) { sleep $time; print; }
    By the way, I changed your $_ to $FH, because it was screwing with the $_ that's the default variable in a loop. I don't know how that didn't mess you up in your code... but it did when I tried it.
Re: Looping line-by-line through STDIN before EOF is received
by elwarren (Priest) on Aug 22, 2000 at 02:54 UTC
    Did you look at the eof function? I would imagine it will help with what you're doing, the example code looks similar to what you're attempting.