foreach my $targetServer (@targets) { # Ping host to check its available my $p = Net::Ping->new(); if ($p->ping($targetServer)) { my @subs; ### Accumulate the deployRoutines here foreach my $deploySection (@deployments) { if ($flagDeploy) { my $deploySource = "$config{$deploySection}{'Source'}" ; my $deployDest = "$config{$deploySection}{'Destination'}" ; if ($flagNoMove) { ## Add this sub to the array to be executed for this server push @subs, sub { deployRoutine($targetServer, $deploySource, $deployDest, "true") }; $threadDetails{$thread}{"Section"} = "$deploySection"; $threadDetails{$thread}{"Target"} = "$targetServer"; } else { ## Add this sub to the array to be executed for this server push @subs, sub { deployRoutine( $targetServer, $deploySource, $deployDest ) }; $threadDetails{$thread}{"Section"} = "$deploySection"; $threadDetails{$thread}{"Target"} = "$targetServer"; } } } ## Now start one thread to execute them all; serially push @threads, threads->new( sub { $_->() for @subs; } ); $p->close(); } #### { use threads; my @subs = map{ eval "sub{ print $_; }" } 1 .. 10; threads->new( sub{ $_->() for @subs; } ); sleep 10; };; 1 2 3 4 5 6 7 8 9 10