I'm trying to select the maximum element from a list according to some arbitrary criteria.

Basically what I'd like to be able to do is something like

$max_el = max { complex_calculation($_) } @list;

and have $max_el be the element for which complex_calculation reported the highest value

Unfortunately the max in List::Util doesn't take a block.

I was able to cobble something together with List::Util::reduce but this seems less than ideal.

$max = reduce { complex_calculation($a) > complex_calculation($b) ? $a + : $b };

My problems with this approach are
1.) complex_calculation() is called twice for each element in the list
2.) the code is less readable & less concise than it could be
3.) this seems like I'm reinventing the wheel.

Does anyone know of a CPAN module or library that will encapsulate this type of functionality?

I've googled by couldn't find anything.

Thanks,


In reply to List::Util max with block by dlarochelle

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.