Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello! I am trying to get sum of all the return values. But its printing only the last value.
my ($thr, $total_count); sub create_file { my $count = shift; open(FH, ">$count"); close(FH); return $count; } foreach my $count (1 .. 5) { $thr = threads->create(\&create_file, $count); } foreach my $t (threads->list()) { $ret = $t->join; $total_count += 1; } print "Total count : $total_count \n";
Appreciate your help. TIA.

Replies are listed 'Best First'.
Re: Threads reinitializing the variable
by choroba (Cardinal) on Aug 05, 2013 at 14:20 UTC
    It is not the last value, it is the count. To get the actual sum, you must use the returned value somehow:
    $total_count += $ret;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Threads reinitializing the variable
by Loops (Curate) on Aug 05, 2013 at 14:22 UTC
    Looks like you're getting a proper count but throwing away all but the last return value... maybe you want to sum them all instead:
    $ret += $t->join;
Re: Threads reinitializing the variable
by rjt (Curate) on Aug 05, 2013 at 14:24 UTC

    This will output Total count : 5, because you only increment $total_count by one on each iteration. You probably want $total_count += $ret instead (or $total_count += $t->join, if you won't be using the return value for anything else, i.e.):

    $total_count += $_->join for threads->list; print "Total count : $total_count \n"; __END__ Total count : 15
    use strict; use warnings; omitted for brevity.