Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Control Structure problem, mistake can't be found

by eosbuddy (Scribe)
on Aug 22, 2008 at 23:22 UTC ( [id://706341]=note: print w/replies, xml ) Need Help??


in reply to Control Structure problem, mistake can't be found

It seems to work for me (cause I artificially made it to work). Some possible bugs are that your increment $i++; works only if expression is true - but this maybe what you intend to do as well. It would be helpful if you could post some errors:
#!/usr/bin/perl use strict; use warnings; my @incorrect; my @correct = qw / 1 2 3 4 5 6 7 8 9 10 /; my $guess = 1; my $i = 0; if ($guess eq $correct[$i]) { # if guess is correct, reply print "You Rock!\n"; $i++; } else { print "You Suck!\n"; # if incorrect, reply and save answer to be calcu +lated @incorrect = (@incorrect, $guess); }

Replies are listed 'Best First'.
Re^2: Control Structure problem, mistake can't be found
by koolgirl (Hermit) on Aug 23, 2008 at 00:45 UTC
    I do have
    chomp($guess = <STDIN>);
    at the top, before the piece I posted. When I run the program as is, this is my output:
    Name the definitive rock band.. The Who You Suck! What is their best song? Moonlight Mile You Suck! What is their best album? Sticky Fingers You Suck! You Rock!
    As you can see, no matter correct, or incorrect, always get "You Suck", then I have to enter an extra \n at the end to end the loop, after that, three lines later, it says "You Rock!, for no reason whatsoever. So, here's the whole code:
    #!usr/bin/perl use strict; my @questions = ("Name the definitive rock band.." , "What is their be +st song?" , "What is their best album?"); my @correct = ("The Rolling Stones" , "Moonlight Mile" , "Sticky Finge +rs"); my $grade = 100 - length(my @incorrect) * 33.3; my @incorrect; my $i = 0; my $guess; # This program asks user three questions, then grades the user's ans +wers. while ($i <= scalar(@incorrect)) { # loop through questions print $questions[$i] . "\n"; chomp($guess = <STDIN>); $i++; if ($guess eq $correct[$i]) { # if guess is correct, reply print "You Rock!\n"; $i++; } else { print "You Suck!\n"; # if guess is incorrect, reply and save +answer to be calculated @incorrect = (@incorrect, $guess); #while ($guess ne @correct[$i]) { # if guess is incorrect, pro +mpt user to try again # print "Try again!\n"; # chomp($guess = <STDIN>); # $i++; # } # end while } # end if } # end while print $grade . "\n"; # calculate and print user's grade print "\nRockstar Programming Inc. All Rights Reserved";

    Note the loop commented out at bottom is a whole other topic, just included it so ya'll could see, because I certainly don't understand this output at all.

    Also, eosbuddy, is this, I'm assuming a regular expression?

    my @correct = qw / 1 2 3 4 5 6 7 8 9 10 /;
    I do know what they are, lol, just not used to seeing that type at this point. I can't use them, but it is helpful to see how you put my data together to make it work.

    But, does anyone understand this output I'm getting? I know my knowledge is very limited, but I just can't seem to place my mistake. There are, I'm sure several re-writes I could do, but I really want to understand why this won't work, to further my skill in the language, because theoretically I really think it should??

    Also, please note that my output includes me entering answers as the user, I entered correct and incorrect to show that it didn't change the response.

    Also, I am very much aware of how useless a trivia game is written this way, especially without any regular expressions. It's more of a learning exersise, to give me a small example of doing something on my own in Perl, and I also do know a bit more these days, but regardless of the fact that it is a useless game lol, I want to understand my mistake more for the experience than the game :)

      Your problem is here:
      $i++; if ($guess eq $correct[$i]) { # if guess is correct, reply
      Array indices in Perl start with 0. You are incrementing $i before you use it as an index to check the first answer. So the "correct" answer to the first question you ask should be "Moonlight Mile" ... ;-)
      You are suffering from premature incrementation :)

      And, for goodness' sake, use warnings;. This would have shown you that you incremented past the end of your @correct array (the first index of an array in perl is 0, not 1). I added these print statements to show the problem:

      print "guess=$guess=\n"; print "correct[$i]=$correct[$i]=\n"; if ($guess eq $correct[$i]) { # if guess is correct, reply print "You Rock!\n"; $i++;

      broomduster and toolic provided the solution, I just want to emphasize what broomduster said in another post in this thread: Learn to use print to debug your program.

      If you had printed both of the comparision operands, $guess and $correct[$i] (and whatever else seemed interesting), you could have solved the riddle by yourself. And as you surely know, you best learn from things you find out yourself.

      AAHHH, I see said the blind man! Thank you so much! lol, I really had a sneaky suspicion that is was a trivial problem, but I just couldn't find it. By the way, I can't use warnings at the moment, I'm on windows, and coding in editpad with the Perl interpreter, and my version is 5.0, so it doesn't pick it up :\

      Anyways, thank you all so much for replying and helping me over that hump :)

        If you mean use warnings; by itself causes problems (as in warnings pragma unknown to perl interpreter), then invoke the program with -w flag (perl -w program-file). Failing that, set $WARNING to a true value ($WARNING = 1;).
      As has already been pointed out by oshalla, you don't want to use length on an array, but rather scalar. A few other important notes:
      • Every time you my a variable, you get a fresh variable. This means that you (almost) never want to use two mys in the same scope. For example, if you typed
        my $a = 1; my $a;
        then you would find that $a was uninitialised.
      • qw// is a quoting operator that takes a string and splits it on whitespace, putting the result into an array. In our case, qw/1 2 3 4/ evaluates to the array (1, 2, 3, 4). The reason that they make you think of regular expressions is that /EXPR/ is short for m/EXPR/, the matching operator. The slashes (in qw//, m//, and other quote-like operators) can be changed to any of (), [], {}, or any repeated delimiter that you choose (like qw+1 2 3 4+)—although be careful if you use '' or ##.
      • @array = (@array, $new_entry) is more idiomatically written as push(@array, $new_entry). See push.

      qw> is the "quote words" operator. It lets you do nifty stuff like:

      my @foo = qw( key west florida orange juice beverage ); # this is identical to: my @foo1 = ( 'key', 'west', 'florida', 'orange', 'juice', 'beverage', );

      See perlop, specifically, the section on Quote and Quote-like Operators" for more info.

      You should consider using push instead of recopying the array:

      # @incorrect = (@incorrect, $guess); push @incorrect, $guess;

      When I was first learning, the single most useful piece of the documentation was the list of functions by category in perlfunc--although I used the version in my copy of Perl in a Nutshell. Anytime I felt like I was doing something awkward or that there might be a better way to do something, I'd look for a built in function to accomplish it.

      Useless little toy programs are an excellent way to start. At the beginning of a big project I'll usually build several useless, little toy programs to test my ideas--only I've learned to call the toys "prototypes", because that sounds better. As a beginner, you are building the prototypes for ALL your future programs.


      TGI says moo

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://706341]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-19 13:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found