I want to send a command, for example, execute a ping:
ping google.es -n 500
I can execute the command with:
my $command = "ping google.es -n 500";
system($command);
And I will get the output printed while it runs.
I can store it into a variable with:
my $command = "ping google.es -n 500";
my $output = `$command`;
But how can I get the output of the command WHILE it is running and then use the output in a variable?
I´ve see a solution like this, but it does not work. It runs the script and when it has finished it will print the result:
my $variable = '';
open my $command_pipe, "-|", $command or die "Pipe from $command failed: $!";
while (<$command_pipe>) {
print $_;
$variable . = $_;
}
UPDATE: Example to show the problem. I have 2 perl scripts and one calls the other:
test.pl:
use strict;
use warnings;
my $command = 'perl test2.pl';
print "Localtime: " . localtime() . "\n";
my $variable = '';
open my $command_pipe, "-|", $command or die "Pipe from $command failed: $!";
while (<$command_pipe>) {
print "[" . localtime() . "] " . $_;
$variable .= $_;
}
print "Localtime: " . localtime() . "\n";
print "Loop finished:\n$variable\n";
Second file test2.pl:
use strict;
use warnings;
print "Waiting 10 sec\n";
my $i = 0;
while($i < 10){
sleep(1);
print "$i\n";
$i++;
}
print "That's it!\n";
And the output is:
C:\Users\****\Desktop\****>perl test.pl
Localtime: Wed Oct 17 13:47:06 2018
[Wed Oct 17 13:47:16 2018] Waiting 10 sec
[Wed Oct 17 13:47:16 2018] 0
[Wed Oct 17 13:47:16 2018] 1
[Wed Oct 17 13:47:16 2018] 2
[Wed Oct 17 13:47:16 2018] 3
[Wed Oct 17 13:47:16 2018] 4
[Wed Oct 17 13:47:16 2018] 5
[Wed Oct 17 13:47:16 2018] 6
[Wed Oct 17 13:47:16 2018] 7
[Wed Oct 17 13:47:16 2018] 8
[Wed Oct 17 13:47:16 2018] 9
[Wed Oct 17 13:47:16 2018] That's it!
Localtime: Wed Oct 17 13:47:16 2018
Loop finished:
Waiting 10 sec
0
1
2
3
4
5
6
7
8
9
That's it!
As you can see everything is just printed after the 10 seconds of the second script.