Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: I think Perl ruined me as a programmer

by mreece (Friar)
on Nov 24, 2007 at 00:51 UTC ( #652692=note: print w/replies, xml ) Need Help??


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 }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://652692]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2019-07-20 07:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?