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.
if ($current > $max) {
to
if ( not defined $max or $current > $max) {
$max would simply stay undef if all values were even.
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; }
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 |