etheleon has asked for the wisdom of the Perl Monks concerning the following question:
however, i noticed that the number of output files are not consistent with the size of my input ie. my array input_data. i would get 96 output files, thereafter 97, and finally 100, if i rerun the problem without deleting the output files. what's wrong?#!/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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using MCE to write to multiple files.
by Anonymous Monk on Nov 22, 2014 at 03:04 UTC | |
by etheleon (Novice) on Nov 22, 2014 at 03:57 UTC | |
by Anonymous Monk on Nov 22, 2014 at 05:03 UTC | |
by BrowserUk (Patriarch) on Nov 22, 2014 at 13:23 UTC | |
by marioroy (Prior) on Dec 13, 2014 at 01:42 UTC | |
by etheleon (Novice) on Nov 24, 2014 at 08:12 UTC | |
by Anonymous Monk on Nov 24, 2014 at 10:32 UTC |