#!/usr/bin/env perl use v5.18; use strict; use warnings; use autodie; use MCE; my @input_data = (0 .. 100 - 1); ## Make an output iterator for gather. Output order is preserved. sub output_iterator { my %tmp; my $order_id = 1; return sub { my ($result, $chunk_id) = @_; $tmp{$chunk_id} = $result; while (1) { last unless (exists $tmp{$order_id}); open my $output, '>', "/path/to/my/files/$chunk_id.txt"; foreach (1..10) { print $output "\t",fibonacci($_)}; say $output; close $output; delete $tmp{$order_id++}; } }; } ## Use $chunk_ref->[0] or $_ to retrieve the element. my $mce = MCE->new( chunk_size => 1, #setting to 1 = do not chunk max_workers => 8, #number of CPU cores gather => output_iterator(), #the function which will be applied to each element of the array ); MCE->foreach( \@input_data, sub { my ($mce, $chunk_ref, $chunk_id) = @_; my $result = sqrt($chunk_ref->[0]); MCE->gather($result, $chunk_id); }); sub fibonacci { my $n = shift; return undef if $n < 0; my $f; if ($n == 0) { $f = 0; } elsif ($n == 1) { $f = 1; } else { $f = fibonacci($n-1) + fibonacci($n-2); } return $f; }