Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Two related questions:
1. What is the best way to find the minimum value in a list ? (sort @_)[0] is clean, but seems wasteful. I'm surprised there doesn't seem to be a built-in MIN function. Is there a clever way with map and a?b:c or something ?
2. What is the best way to find the INDEX of the minimum value in a list ? (If there are duplicates, any of their indecies are OK).
Thanks :)

Replies are listed 'Best First'.
Re: find minimum in list
by broquaint (Abbot) on Feb 10, 2004 at 14:00 UTC
    Check out List::Util which became a core module as of 5.7.3
    my $min = min @list; my $idx = first { $list[$_] == $min } 0 .. $#list; ## or for duplicates my(@idxs) = grep { $list[$_] == $min } 0 .. $#list;
    HTH

    _________
    broquaint

      Great tips, thanks!
Re: find minimum in list
by Limbic~Region (Chancellor) on Feb 10, 2004 at 14:02 UTC
    Anonymous Monk,
    While there is a module that has just the function you are looking for, your second question leads me to offer the "low water mark" solution.
    #!/usr/bin/perl use strict; use warnings; my @list = qw(4 78 3 89 4 1000 5); my %minimum; for my $index ( 0 .. $#list ) { @minimum{ qw(index min) } = ($index , $list[$index]) if ! %minimum; if ( $list[$index] < $minimum{min} ) { @minimum{ qw(index min) } = ($index , $list[$index]); } } print "The index of the smallest number is : $minimum{index}\n"; print "The valud of the smallest number is : $minimum{min}\n";
    Cheers - L~R
A reply falls below the community's threshold of quality. You may see it by logging in.