Perl: how can I capture the output in a variable at the same time by showing it in the standard output?


I started working on a perl script and I'm calling external rsync application to do a backup. I want to capture the output of the rsync action and I'm using this format:

print "Starting backup. Please wait...\n";
my @output = `rsync -avut /home /media/drive/`;

At this point, the script is running as is supposed to, but the action of the rsync is captured into my array and I can't see the progress. Is there a way to capture the output as above, but also show it in my console?

The backticks capture STDOUT and places it in your array.

If you want to see STDOUT as well as capture it in a variable, you could use open().

I think something like this might work?

my $output;
print "Starting backup. Please wait...\n";
open(RSYNC, "-|", "rsync -avut /home /media/drive")
    or die "Can't exec rsync : $!";
  print $_;
  $output .= $_;