Skip to content

Instantly share code, notes, and snippets.

@leedo
Created November 2, 2012 19:30
Show Gist options
  • Save leedo/4003808 to your computer and use it in GitHub Desktop.
Save leedo/4003808 to your computer and use it in GitHub Desktop.
AnyEvent directory scanner
sub scan_dir {
my ($path, $filter, $cb) = @_;
my (@queue, @matches);
my $cv = AE::cv;
my $enqueue = sub {
$cv->begin;
push @queue, shift;
};
$enqueue->($path);
my $scan = sub {
my $path = shift;
aio_scandir $path, 0, sub {
my ($dirs, $nondirs) = @_;
for (@$nondirs) {
push @matches, "$path/$_" if $filter->("$path/$_");
}
$enqueue->("$path/$_") for @$dirs;
$cv->end;
};
};
my $t = AE::idle sub {
if (my $dir = pop @queue) {
$scan->($dir);
}
};
$cv->cb(sub {
eval {shift->recv};
undef $t;
if ($@) {
warn "scanner stopped";
return;
}
$cb->(\@matches);
});
return $cv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment