The "classical way" is to set up a variable for $min, and a variable for $min_index, then to iterate through your array by index, and any time the element at a given index is less than $min, set $min equal to that element, and $min_index equal to the current index. At the end of the loop, $min_index will contain the correct value. In Perl, undef is less than any defined value, so you don't strictly need to deal with explicitly populating $min on the first iteration, or doing a definedness check, but you will get some warnings if you don't test definedness first.

That's the classical method; the one taught to beginning programmers almost regardless of which language they're using as the means of learning programming. And it's probably the method you've discussed in class. If the class discussion was inadequate, a little searching might have turned up How can I find the index of the biggest element in an array?, which provided some good solutions which can be adapted to find the minimum instead pretty easily. Here's one based on GrandFather's answer in that thread:

my @array = ( 1, 5, 7, 9 ); sub minindex { my( $aref, $idx_min ) = ( shift, 0 ); $aref->[$idx_min] < $aref->[$_] or $idx_min = $_ for 1 .. $#{$aref}; return $idx_min; } print minindex(\@array), "\n";

Dave


In reply to Re: index of the minimum element of the array by davido
in thread index of the minimum element of the array by Anonymous Monk

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.