because you mask original $imax inside the loop with my $imax=$i...

Below is a more esoteric way to do it without a function. It goes under the "Schwartzian transform":

my @arr = (1,2,3,5,10,3,4,300,1,2,-2); my ($i) = map { $_->[0] } sort { $b->[1] <=> $a->[1] } map { [ $_ , $a +rr[$_] ] } 0..$#arr; print "i=$i\n"; # index 7 => value 300

starting from right to left, create an array of all the indices in your array, package the index and its value into a temporary arrayref and then into an intermediate array, sort that intermediate array with custom sort function which sorts in reverse (i.e. biggest first) wrt the second element in said packaged arrayref (which is the value). Remember index and value are still packaged together, so extract the index (first item of the arrayref) with the leftmost map which returns an array of indices of the items in your original array sorted by their value. However my ($i) = ... will retain only the first item (the index with largest value) and skip the rest.

sort of...

bw bliako

Edit: changed $#arr-1 to $#arr, thanks AnomalousMonk


In reply to Re: Why does my get_max_index function return zero? (High Water Mark Algorithm) by bliako
in thread Why does my get_max_index function return zero? (High Water Mark Algorithm) by hghosh

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.