in reply to Re: John Guttag's book - 2nd exercise. My attempt in Perl.
in thread John Guttag's book - 2nd exercise. My attempt in Perl.

you can avoid the first loop if you change

if ($current > $max) {

to

if ( not defined $max or $current > $max) {

$max would simply stay undef if all values were even.


no it's more complicated ... wait
This should do:
use strict; use warnings; my @array = ( -11, -13, 4, 22, 17); print "Result: ",find_max_odd(@array) // "undefined", "\n"; sub find_max_odd { my $max; for (@_) { next unless $_ % 2; unless ( defined $max ) { $max = $_; next; } $max = $_ if $_ > $max; } return $max; }

I was confused, but becaus eof short-circuiting of the or the first idea should do too:
use strict; use warnings; my @array = (-11,-13,4, 22, 17); print find_max_odd(@array), "\n"; sub find_max_odd { my $max; while (my $current = shift) { next unless $current % 2; if (not defined $max or $current > $max) { $max = $current; } } return $max // "undefined"; }

Replies are listed 'Best First'.
Re^3: John Guttag's book - 2nd exercise. My attempt in Perl.
by Laurent_R (Canon) on May 21, 2017 at 09:27 UTC
    Yeah, KurtZ, I definitely agree with you that it can be made simpler (++), and I most likely wouldn't code this the way I have shown.

    I only suggested a solution that used only very basic Perl knowledge since it was what the OP was asking for. Also, having two loops did not bother me too much, since they're browsing the array items only once anyway.