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.

perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.