One thing I see is that $hash_ref seems to be constant, so you can compute the list of keys once instead of each time: @keys = keys %$hash_ref; and for my $key (@keys)

And if several $a values can share $b sub values, you can keep the subsums in cache to avoid recomputing them (untested because you didn't provide sample data):

use List::Util qw( sum ); my %cache; my @keys = keys %$hash_ref; foreach my $a_ (@{ $array_ref }) { my $i = 0; foreach my $b_ (split('-', $a_)) { $i += $cache{$b_} //= sum map { $_->{value} } @{ $foo->{$b_} } +{@keys}; # Use the cached value or compute the sum } push @{ $bar->{$i} }, $a_; }
Using the orcish manoeuver, List::Util, and a slice

I suppose the name are only because this is an example? Even in a example I would avoid $a and $b, (even more so when using List::Util) because of their special meaning. (Edit) And I avoid single char names as a general rule

Edit $hash_ref->{$b_ } should have been $foo->{$b_}. Thanks kcott


In reply to Re: Optimize a perl block by Eily
in thread Optimize a perl block by IruP

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.