http://qs321.pair.com?node_id=652692


in reply to Re: I think Perl ruined me as a programmer
in thread I think Perl ruined me as a programmer

that min functions looks kinda funny, and in some ways manages to expose the dangers of writing lazy (ie, terse) perl.
sub min { my $min = shift; foreach (@_) { $_ = $min if $_ < $min; } return $min; } @a = (10, 5, 8, 2, 1, -4); $min = min(@a); print "min of @a is $min\n";
produces: min of 10 10 10 10 10 10 is 10

probably not what you expected! not only did it give the wrong answer, it destroyed the input list!

Replies are listed 'Best First'.
Re^3: I think Perl ruined me as a programmer
by Anonymous Monk on Nov 14, 2008 at 23:51 UTC
    The function should be:
    sub min { my $min = shift; foreach (@_) { $min = $_ if $_ < $min; } return $min; }
      or, to avoid warnings about the occasional undefs in your arg list:
      sub min { my $min; for (@_) { next unless defined; $min = $_ if $_ < $min } $min }
        oops, sorry..
        sub min { my $r; for (@_) { next unless defined; $r = $_ if !defined($r) || $_ < $r } $r }