use 5.010; use strict; use warnings; use Symbol qw/gensym/; sub spawn_worker(&) { my ($thunk) = @_; my $pipe = gensym; my $pid = open $pipe, '-|'; die "Unable to create worker: $!" unless (defined($pid)); if ($pid == 0) { $thunk->($pipe); exit 0; } else { return ($pid, $pipe); } } sub collect_work($*) { my ($pid, $pipe) = @_; my $_; print "$pid >> $_" while (<$pipe>); die "Unable to read from worker $pid: $!" if ($!); close $pipe or die "Unable to close worker $pid: $!"; } my %workers = (); for my $idx (0..10) { my ($pid, $pipe) = spawn_worker { print "Hello, I'm worker $idx\n"; }; $workers{$pid} = $pipe; } while (my ($pid, $pipe) = each %workers) { collect_work $pid, $pipe; }