Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is slightly modified version of OMG_peanuts with for and less variables:</p> <pre><code>my $len = length $array[0]; my $longest = 0; for my $i (1 .. $#array) { my $i_len = length $array[$i]; if($i_len &gt; $len) { $longest = $i; $len = $i_len; } } my $l = $array[$longest]; </code></pre> <p>I was playing a bit with benchmarks, getting this for small numbers (original array)</p> <pre><code> Rate REDUCE TMPVAR TMPFOR REDUCE 234862/s -- -0% -7% TMPVAR 235643/s 0% -- -6% TMPFOR 251326/s 7% 7% -- </code></pre> <p>and this for larger number or items (original array <code>x 100</code>)</p> <pre><code> Rate TMPVAR TMPFOR REDUCE TMPVAR 3242/s -- -28% -32% TMPFOR 4503/s 39% -- -5% REDUCE 4750/s 47% 5% -- </code></pre> <p>Note that suitability of algorithm heavily varies due to data specifics (I would guess longer strings may increase weight of <code>length</code> function in algorithm).</p> <p><strong>EDIT</strong>: Here is full code for the benchmark (long array version, short is missing <code>x 100</code> in array definition)</p> <pre><code>use Benchmark qw(:all); use List::Util qw(reduce); my @array = qw( one two three four five six seven eight nine ten eleven ) x 100; cmpthese(-2, { REDUCE =&gt; sub { my $l = reduce{ length($a) gt length($b) ? $a : $b } @array; }, TMPVAR =&gt; sub { my $idx = 1; my $lastLength = length $array[0]; my $lastElt = $array[0]; my $listLength = scalar @array; while ($idx &lt; $listLength) { my $tmpLength = length $array[$idx]; if ($tmpLength &gt; $lastLength) { $lastElt = $array[$idx]; $lastLength = $tmpLength } $idx++ } my $l = $lastElt; }, TMPFOR =&gt; sub { my $len = length $array[0]; my $longest = 0; for my $i (1 .. $#array) { my $i_len = length $array[$i]; if($i_len &gt; $len) { $longest = $i; $len = $i_len; } } my $l = $array[$longest]; }, }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload