Well, you are testing in each iteration whether $guess is defined. But that's not necessary. You know that $guess is undefined the first time around, and then never again.

Also, people have suggested that you turn on warnings, but they fail to mention that you should do some checking of $guess (to see whether it's a number) before comparing it to $secret_number - otherwise, you will get warnings.

#!/usr/bin/perl use strict; use warnings; my $secret = 1 + int rand 100; while (print "Your guess > ") { local $_ = <>; chomp; if (!/\S/ || /quit/i || /exit/i) { print "Too bad, you gave up.\n"; exit; } if (/\D/) { print "You didn't enter a non-negative integer\n"; next; } if ($_ == $secret) { print "You guessed the number correctly.\n"; exit; } my $answer = $_ < $secret ? "less" : "greater"; print "The number you entered is $answer than the secret number\n" +; } __END__

That's how I would do it.

Abigail


In reply to Re: Bad Code? by Abigail-II
in thread Bad Code? by Hayl_

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.