In the code below p00 is a named pipe, created with mkfifo p00.
In console 1, I ran:
% perl -ne 'print "PERL: $_"' < p00
Then, while the above blocked (as expected), in console 2 I ran
% seq 3 > p00
As a result, the following appeared in console 1:
PERL: 1
PERL: 2
PERL: 3
%
This was almost the result I had hoped to achieve, except for the fact that the perl script terminated after printing the third line.
I want the script to continue echoing lines (prefixed by “PERL: “) as soon as they become available, and block otherwise.
The following variant of the one-liner above superficially resembles the desired behavior:
perl -e 'while ( 1 ) { print "PERL: $_" while <>; sleep 1 }' < p00
…but it’s not the real deal, because it does not block while waiting for input, nor it echoes its input as soon as it is available.
NOTES:
- the motivation behind this question is education (mine, that is) and nothing more; I’m not trying to solve any practical problem; I’m just trying to learn more perl (and unix).
- I wasn’t sure if this question was more suited for unix.se.com; I’m more than happy to re-post it there if it is; just let me know.
After reading Maxim Yegorushkin’s comment I realized that all I had to do was get rid of the
sleep 1in the second version. I.e., this does exactly what I want:As Maxim wrote, the inner loop terminates upon receiving the
EOF; then the outer loop returns the script to a blocking state, waiting for input… Doh!