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

Newbie (I know the rule against no homework question, but . . .) I have to write a complementary pair of routines, min_str() and max_str(), that will return the minimum and maximum terms in a sorted list by location, not lenght. Minimum being the first and Maximum being the last. Would using the "gt" and "lt" operators be the better way?

Replies are listed 'Best First'.
Re: Rountines
by bmhm (Beadle) on Sep 20, 2000 at 02:47 UTC
    This is what I have so far
    #!usr/bin/perl -w use strict; my @list = (26, 3, 53, 65, 9, 101, 19); @list = sort( @list ); min_str(); max_str(); sub min_str { print "n\"; print "$list[0]\n"; } sub max_str { print "$list[7]\n"; }
    Needless to say this has many errors.
      Bonus points for using strict.

      Some other things you might not know, you can get the last index generically (not using 7). Do some research, and if you still can't figure it out... I'll tell you. Also, read the man page for sort. It will show you how to sort the way you want.

      Oh, and one other thing. Don't print from within your subroutines... have them return the string, and print the return value:
      print min_str( @strings );

Re: Rountines
by merlyn (Sage) on Sep 20, 2000 at 05:13 UTC
    If you only want the min and max of a list of strings, sorting is not very efficient. Check out List::Util, which has a nice minstr and maxstr function. If you want to make only one pass, you can use the C-coded reduce from there, and still get some decent speed:
    use List::Util qw(reduce); my $min_max = reduce { my ($min, $max) = ref $a ? @$a : ($a, $a); $min = $b if $min gt $b; $max = $b if $max lt $b; [$min, $max]; } @your_list_here; my($min, $max) = @$min_max;

    -- Randal L. Schwartz, Perl hacker

Re: Rountines
by japhy (Canon) on Sep 20, 2000 at 02:37 UTC
    No. The gt and lt string operators deal with ASCIIbetical ordering. "ABC" is less than "a". You need to deal with string length, not contents.

    $_="goto+F.print+chop;\n=yhpaj";F1:eval
RE: Rountines
by johannz (Hermit) on Sep 20, 2000 at 03:20 UTC

    If you have a copy of the perl cookbook, section 4.1.5 'Sorting a List by Computable Field' will be helpful. You can also use the perlmonks faq, How do I sort an array by (anything)?.

    In short, the sort routine can take a subroutine argument that allows you to define your comparison operation. If this operation is complex or computationally expensive, you might want to learn about a Schwartzian Transformation. Both of the above links will have some starting points for learning about Schwartzian Transformations.