Hi,
I'm trying to pop elements from an array in parallel until it consumes everything, then have the forks return it back for the next consumers. I can't figure out why I keep on getting the uninitialized value error (below). I thought adding a sleep before the start() would help (I am probably misunderstanding the problem as forks being too fast) but it only helped to a certain extent (compared to not having a sleep at all).
#!/usr/bin/perl
use strict;
use warnings;
use Parallel::ForkManager;
my @keycards= qw(A B C);
my @users = qw(peter james john luke andrew judas);
my $pm = Parallel::ForkManager->new(3);
$pm->run_on_finish(
sub {
my $key = $_[5]->{key};
unshift(@keycards, $key);
}
);
foreach my $user (@users) {
sleep(int(rand(3)));
my $key = pop(@keycards);
$pm->start and next;
print "$user took the '$key' key\n";
$pm->finish(0, { key => $key });
}
$pm->wait_all_children;
[user@localhost ~/bin]$ perl a.pl
peter took the 'C' key
james took the 'B' key
john took the 'A' key
luke took the 'C' key
andrew took the 'B' key
judas took the 'A' key
[user@localhost ~/bin]$ perl a.pl
peter took the 'C' key
james took the 'B' key
john took the 'A' key
Use of uninitialized value in concatenation (.) or string at a.pl line
+ 23.
luke took the '' key
andrew took the 'C' key
judas took the 'B' key
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.