I made a simple executable ( string.exe
) from the following code. You can not change this file.
$| = 1;
foreach my $i (1..10) {
print "test : $i\r";
sleep 2;
}
I want grab the output from that program in real-time. I attempted to do so with the following code:
open(my $fh, '-|', 'string.exe') or die $!;
while (my $line = <$fh>) {
print $line;
}
But I can not get the output in real-time. In my opinion, this is due to the use of carriage return ( \\r
).
readline
( <>
) reads until a line feed is encountered, but you send carriage returns instead. readline
is somewhat configurable (via $/
), but not to the point where you can instruct it to read until a CR or LF is returned.
sysread
, otoh, returns as soon as data is available. This is exactly what you want.
$| = 1;
while (sysread($fh, my $buf, 64*1024)) {
print $buf;
}
You can set your $INPUT_RECORD_SEPARATOR
to \\r
:
local $/ = "\r";
while (my $line = <$fh>) {
how to get windows command line string?
If I understand your question, you could use something like
local $cmd = join " ", $0, @ARGV;
print $cmd;
Testing choroba 's answer about the $INPUT_RECORD_SEPARATOR
:
use strict;
use warnings;
# As described in http://perldoc.perl.org/perlipc.html#Safe-Pipe-Opens
my $pid = open(KID_TO_READ, "-|") // die "can't fork: $!";
# Parent
if ($pid) {
local $/ = "\r";
while (<KID_TO_READ>) {
use Data::Dump;
dd $_;
}
close(KID_TO_READ) or warn "kid exited $?";
# Child
} else {
local $| = 1;
foreach my $i (1..10) {
print "test : $i\r";
sleep 2;
}
exit;
}
Outputs:
"test : 1\r"
"test : 2\r"
"test : 3\r"
"test : 4\r"
"test : 5\r"
"test : 6\r"
"test : 7\r"
"test : 8\r"
"test : 9\r"
"test : 10\r"
Ironically, this test won't work on Windows:
'-' is not recognized as an internal or external command,
operable program or batch file.
kid exited 256 at test_RS.pl line 14.
However, this still confirms that the $RS
will work as documented.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.