Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: how to enable, disable strict

by marto (Cardinal)
on Apr 25, 2007 at 09:31 UTC ( [id://611946] : note . print w/replies, xml ) Need Help??


in reply to how to enable, disable strict

A couple of things in addition to the advice shmem has already given. Firstly you are not checking if the number the user has guessed is the secret number, just that it is a lower number, and you never tell the user that they have guessed correctly. Try the code below:
use strict; use warnings; my $secret=42; my $guess; while(1) { print "please enter a guess from 1 to 100: "; chomp($guess = <STDIN>); if ($guess =~ /quit|exit|^s*$/i){ print " sorry you gave up.the number was $secret.\n"; last; } if ($guess != $secret) { print "Wrong! Guess again.\n"; }else{ print "Correct!\n"; last; } }
In your example if the secret number was 42 and the user enters 43 they are not told that they have failed to guess correctly.
Please read the PerlMonks FAQ and How do I post a question effectively? if you have not alreay done so.

Hope this helps

Martin

Replies are listed 'Best First'.
Re^2: how to enable, disable strict
by elsiddik (Scribe) on Apr 25, 2007 at 10:20 UTC
    now i have the code completed -- but when a user guess the right number it keeps asking for the same guess again and again , my question is : how can i restart the program automaticaly with a new secret number but without quiting . here is the code
    #!/usr/bin/perl -w use warnings; use strict; my $secret = int(1 + rand 100); while(1) { print "please enter a guess from 1 to 100: "; chomp(my $guess = <STDIN>); if ($guess =~ /quit|exit|^s*$/i) { print " sorry you gave up.the number was $secret.\n"; last; } elsif ($guess < $secret) { no strict; print "you failed ,try higher\n"; } elsif ($guess > $secret) { print "you failed , try lower\n"; } elsif ($guess == $secret) { print "you got it\n"; } }
    Sorry again for the mistakes i made concerning where should i add my question , im new here and new for PERL in general. cheers,

      There are many ways to achieve that. An easy way is to repeat the code that generates of the number in the success block. Here's a slightly different way to do it using a "special" value (undef) and using an if as a statement modifier:

      #!/usr/bin/perl -w use warnings; use strict; my $secret; while (1) { $secret = int(1 + rand 100) if ! defined $secret; print "please enter a guess from 1 to 100: "; chomp (my $guess = <STDIN>); if ($guess =~ /quit|exit|^s*$/i) { print "Sorry you gave up. The number was $secret.\n"; last; } if ($guess < $secret) { print "You failed, try higher.\n"; } elsif ($guess > $secret) { print "You failed, try lower.\n"; } elsif ($guess == $secret) { print "You got it!\n"; $secret = undef; } }

      DWIM is Perl's answer to Gödel
        its working perfectly now ;) thx dude.