我是编程语言的初学者。我第一次使用run_on_finish回调hashref。我做得对吗?我尝试发送哈希到parrent并合并键和值与此哈希的其余值。我希望得到完全相同的哈希,而不使用ForkManager和子进程。
use Hash::Merge qw/merge/;
use Parallel::ForkManager;
use Data::Dumper;
my $pm = Parallel::ForkManager->new(10);
my %hash;
$pm->run_on_finish(sub {
my ($pid,$exit_code,$ident,$exit_signal,$core_dump,$data)=@_;
%hash = %{ merge( \%hash, \$data->{$i} ) };
print "TEST: $data->{$i} \n";
});
my @tablica = ('jeden', 'dwa', 'trzy');
foreach (@tablica) {
my $pid = $pm->start and next;
$rsdev{$_} = localtime;
$pm->finish(0, \%rsdev);
}
print Dumper \%hash;
输出
perl "untitled.pl"
TEST:
TEST:
TEST:
$VAR1 = {};
我试图获得这样的输出:
$VAR1 = {
'jeden' => 'Mon Mar 26 17:26:01 2018',
'dwa' => 'Mon Mar 26 17:26:01 2018',
'trzy' => 'Mon Mar 26 17:26:01 2018',
};
我不知道为什么但$ data-> [0]值为空。我做错了什么?
答案 0 :(得分:1)
my (...) = @_;
应位于子
您返回的值也比需要的要复杂得多。
修正:
use Parallel::ForkManager qw( );
my $pm = Parallel::ForkManager->new(10);
my %rsdevs;
$pm->run_on_finish(sub {
my ($pid, $exit_code, $id, $exit_signal, $core_dump, $rsdev) = @_;
warn("Child $id killed by signal $exit_signal"), return if $exit_signal;
warn("Child $id exited with error $exit_code"), return if $exit_code;
warn("Child $id encountered an unknown error"), return if !$rsdev;
$rsdevs{$ident} = $rsdev;
});
my @tablicas = ('jeden', 'dwa', 'trzy');
for my $id (@tablicas) {
my $pid = $pm->start($id) and next;
my $rsdev = { ts => "".localtime, foo => rand };
$pm->finish(0, $rsdev);
}
$pm->wait_all_children;
答案 1 :(得分:0)
use Parallel::ForkManager qw();
use Data::Dumper qw(Dumper);
my $pm = Parallel::ForkManager->new(10);
my %hash;
$pm->run_on_finish(sub {
my $data = pop @_;
%hash = (%hash, %$data);
});
my %rsdev;
for my $i (0..9) {
my $pid = $pm->start and next;
$rsdev{$i} = localtime;
$pm->finish(0, \%rsdev);
}
$pm->wait_all_children;
print Dumper \%hash;
__END__
{
'9' => 'Mon Mar 26 18:08:40 2018',
'2' => 'Mon Mar 26 18:08:40 2018',
'5' => 'Mon Mar 26 18:08:40 2018',
'0' => 'Mon Mar 26 18:08:40 2018',
'4' => 'Mon Mar 26 18:08:40 2018',
'8' => 'Mon Mar 26 18:08:40 2018',
'3' => 'Mon Mar 26 18:08:40 2018',
'6' => 'Mon Mar 26 18:08:40 2018',
'7' => 'Mon Mar 26 18:08:40 2018',
'1' => 'Mon Mar 26 18:08:40 2018'
}