in reply to Printing largest number in array using loops and if statement

matze77,
Here are some reasons why sorting the array to find the maximum value is not a good idea:

The implementation you have come up with is usually referred to as the high water mark algorithm. Usually, it looks more like this:

my $max; for (@list) { $max = $_ if ! defined $max || $_ > $max; }

If you know for that no value will be less than a certain number, you can set it to that (as you did with 0) or you can assign it to the first value in the list (as suggested elsewhere in this thread) and then loop through the rest of the list. Many would recommend not re-inventing the wheel and would point you to List::Util.

use List::Util 'max'; print max(@list), "\n";
I wrote How A Function Becomes Higher Order which may be too advanced but keep the link around for when you are ready. Here are some extra credit ideas to make you consider how you might need to modify the water mark algorithm:

Cheers - L~R

Replies are listed 'Best First'.
Re^2: Printing largest number in array using loops and if statement
by matze77 (Friar) on Jan 17, 2010 at 08:39 UTC

    Hmm. I must admit i do not fully understand that line of code, perhaps if written in more lines it is better to understand:

    $max = $_ if ! defined $max || $_ > $max;
    Could one say if $max is not defined (set to a value maybe this could occure on first iteration?). or $_ is greater than $_max?. Then $max is set to $_?

      Yes, that is what it means. Any time you have stmt if cond, it can be rewritten as
      if (cond) { stmt; }
      So, in this case, that line is equivalent to
      if (! defined $max || $_ > $max) { $max = $_; }
      Personally, I prefer the method of initializing $max to the first (defined) item in the list so as to avoid testing !defined $max on every pass. The performance benefit of avoiding that test is negligible, of course, but it reads more cleanly to me when you're able to just say "remember this as the highest value if it's greater than the previous highest value" without the extra "and a highest value has been previously set" clause.