I'm working with Parallel::ForkManager and I've found that there may be a slight 'flaw' in the design (or my understanding of it) that I need to grasp.

Basically I'm trying to consectively open a file for each child forked, store the results of my forked process in the file and close it. Each file is incremented for each child. Below is a small sample that exhibits this behavior:

use strict; use Parallel::ForkManager; my @ary = (1..100); my $count = 1; my $pm = new Parallel::ForkManager(30); foreach my $val (@ary) { # Without 'and next' works, but is it forking? # $pm->start; $pm->start and next; print "Working on $val (count: $count)\n"; open(ARY, ">$count") or die $!; print ARY "$val, $count"; close ARY; $count++; $pm->finish; };

If I apply one theory: If I have initialized the processing to 30 children, do they all get their first loop through the foreach() here, and hence the count is always '1'?

I notice that if I use '$$' instead of $count, they are indeed all running in their own pid, so that would seem to validate that.

Is there any way to apply an incrementing counter here, one for each child, in the order they were processed? Does removing the 'and next' still fork?

Update: As 3dan suggested, the run_on_start method was exactly what I needed here. Working pseudocode below:

use strict; use Parallel::ForkManager; my @ary = (1..100); my $count = 1; my $pm = new Parallel::ForkManager(30); $pm->run_on_start( sub { my ($pid,$ident) = @_; open(ARY, ">$count") or die $!; print ARY "$count"; close ARY; $count++; } ); foreach my $val (@ary) { $pm->start and next; print "Working on $val (count: $count)\n"; $pm->finish; };

In reply to Odd Parallel::ForkManager behavior by hacker

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.