I'm new to Perl 5 asynchronous processes and find it exciting that CPAN offers similar support that we can do in Node.js with AnyEvent, IO::Async, etc. However, the tutorial provides a few examples for complicated stuff. What I need is only to run an external system command in parallel using AnyEvent.
Am I doing it correctly in the example below to zip a number of files asynchronously? Please don't raise a concern about running the system command zip instead of using CPAN modules; the example is purely to demonstrate the idea of running an asynchronous process...
#!/bin/env perl
use strict;
use AnyEvent;
use AnyEvent::Util;
my $s1 = time;
my $quit_program = AnyEvent->condvar(
cb => sub {
warn "Done async";
}
);
my $result;
$quit_program->begin( sub { shift->send($result) } );
for my $file (@files) {
$quit_program->begin;
my $cv; $cv = run_cmd [qw(zip), "${file}.zip", $file],
"<" , "/dev/null",
">" , "/dev/null",
"2>", "/dev/null";
$cv->cb (sub {
shift->recv and die "command failed";
# undef $cv;
$quit_program->end;
});
}
$quit_program->end; # end loop
my $foo = $quit_program->recv;
say "Total elapsed time: ", time - $s1, " ms";