This is to be tackled using only if/else loop and comparisons, because that is what the author has covered till that part.
Well, the modulo operator should be permitted. We could shortcut with next and unless, but if it hasn't been covered, an inner if() block will do:
use strict; use warnings; my ($x, $y, $z) = (-11,-13,4); my $max; for($x,$y,$z) { # next unless $_ % 2; if ($_ % 2) { $max = $_ unless defined $max; $max = $_ if $max < $_; } } print "max odd: ", $max || "not found","\n";
update: darn, I wrote a for() loop, which ostensibly hasn't been covered up to that point. But why hasn't it?
OTOH, you wrote if/else loop - anyways, to avoid the for() loop, let's unroll it:
use strict; use warnings; my ($x, $y, $z) = (-11,-13,4); my $max = 0; if($x % 2) { if ( ! $max ) { $max = $x; } elsif ($max < $x ) { $max = $x; } } if($y % 2) { if ( ! $max ) { $max = $y; } elsif ($max < $y ) { $max = $y; } } if($z % 2) { if ( ! $max ) { $max = $z; } elsif ($max < $z ) { $max = $z; } } print "max odd: ", $max || "not found","\n";
This would be a good example for introducing loop control, leading to the loop layed out above.
update: made each 2nd if block into elsif, as per choroba's comment below.
In reply to Re: John Guttag's book - 2nd exercise. My attempt in Perl.
by shmem
in thread John Guttag's book - 2nd exercise. My attempt in Perl.
by pritesh_ugrankar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |