est est - 2 months ago 23
Perl Question

How to run external command in parallel using AnyEvent and Perl

I'm new to Perl 5 asynchronous process and find it exciting that CPAN offers a 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 system command zip instead of using CPAN modules; the example is purely to demonstrate the idea of running async 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) {

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; # end loop
my $foo = $quit_program->recv;
say "Total elapsed time: ", time - $s1, " ms";


I assume you mean AnyEvent::Util and not AnyEvent::Tool.

Otherwise, I haven't tried out your program, but it looks like a textbook example of using condvars and run_cmd to me. It certainly is close to what I would write myself (I am the author of AnyEvent), gets the tricky parts right (having an outer begin/end in case @files is empty), does error checking and so on.

So if you ask me, you actually did read the docs and used your knowledge to pass the exam :)