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

Perl Experts: I have the following snippet that doesn't sum all the credits for companies in the hash. The person who helped me used $_, but nothing seems to go into the variable.
foreach $company (sort(keys %details_for)){ my @trans_details = @{$details_for{$company}}; my $comp = $trans_details[0]->{'company'}; my $sumcredits += $_->{'credits'} for (@trans_details); #Show the total credits print $comp, "\t", $sumcredits, "\n"; };
Help over this speed bump would be appreciated. I'm pretty close to finishing this.

Replies are listed 'Best First'.
Re: HofA - Sum Totals
by ikegami (Patriarch) on Feb 22, 2010 at 23:45 UTC

    It's impossible for nothing to go into $_ if the code that uses $_ gets executed. $_ is being aliased to each element of @trans_details in turn, so $_ will contains whatever they contain. If the value of $_ doesn't change, it's because the value of the elements are the same.

    In other words, the bug is elsewhere.

    Update: As kennethk discovered, there is a problem with the code you posted. The problem isn't with $_, though. I wonder how you came to the conclusion that it was.

Re: HofA - Sum Totals
by kennethk (Abbot) on Feb 22, 2010 at 23:40 UTC
    There is nothing obviously wrong with this code and I gain no new insight from reading what I presume was the previous node in this thread, Query Array from Hash. Please give some sample input data, or even better the output generated by Dumper (Data::Dumper) so we can compare the data structure you have to the one your code expects.

    The my is localizing your result to the implicit for loop. Try this instead:

    my $sumcredits = 0; for (@trans_details) { $sumcredits += $_->{'credits'} }
      That worked. It also worked like the following:
      my $sumcredits = 0; $sumcredits += $_->{'credits'} for (@trans_details);
      So the value in how I had it setup before kept on reinitializing every time it went through the loop. Thanks for your help.
Re: HofA - Sum Totals
by Your Mother (Archbishop) on Feb 22, 2010 at 23:43 UTC

    Slight style/syntax mods with debug stub.

    use YAML; for my $company ( sort keys %details_for ) { my @trans_details = @{ $details_for{$company} }; my $comp = $trans_details[0]->{company}; my $sumcredits; $sumcredits += $_->{credits} for @trans_details; # Uncomment to see if the "credits" are there as expected. # print Dump($details_for{$company}); # Show the total credits printf("%20s --> %.2f\n", $comp, $sumcredits); }