Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

copied from Oreilly "Learning Perl" - but the logic doesn't work

Status
Not open for further replies.

LaylaNahar

Programmer
Oct 25, 2006
26
US
Hi - I copied this script from Oreilly's 'Learning Perl'.
I'm pretty sure I copied it accurately, but the logic doesn't work. when you don't guess the secret word, the elsif clause is executed twice in a row, advancing the index to the end of the array, instead of just on to the next item.

I'm wondering if my unfamiliarity with perl is making it difficult for me to spot an obvious error. Can anybody tell why it does this? Thanks.

Code:
#!/usr/bin/perl -wT
@words = ("lama", "alpaca", "camel");
print ("guess the secret word\n");
$guess = <STDIN>;
chomp ($guess);

$i = 0;
$correct = 'maybe';

while ($correct eq "maybe") {
	
	if ($words[$i] eq $guess ) {
		$correct = "yes"; # get out of while
		}

	elsif ($i < 2) {
		$i=$i+1; 
		}
		
	else {print ("Try again please\n");
		$guess = <STDIN>;
		chomp ($guess);
		$i=0;
	}#end else
}# end of while
 
Works ok for me.

I'll go through what happens when the user enters a word that's not in @words. Hopefully this'll answer your query.

-set up the @words array
-print "guess the secret word"
-read the word into $guess
-remove newline from $guess

-set $i to 0: this is the position in the array we check each time
-set the $correct variable to 'maybe'. The while loop will keep going until this changes

-enter the while loop for the first time
-check if position 0 holds the word the user entered: it doesn't
-check if $i is less than 2. It is so increase $i to 1
-skip the "else" because the "elsif" was true

-enter the while loop for the second time
-check if position 1 holds the word the user entered: it doesn't
-check if $i is less than 2. It is so increase $i to 2
-skip the "else" because the "elsif" was true

-enter the while loop for the third time
-check if position 2 (the last position) holds the word the user entered: it doesn't
-check if $i is less than 2: It isn't
-enter the "else" block: print "try again", read in a new word and reset $i to 0 so that we begin checking at the beginning of the array for the next iteration of the while loop

Does that help explain it?
 
Hi - thanks for your reply. I realize now that I was expecting the program to behave in a different way, and so I was seeing exactly the behavior you describe, but interpreting it as a bug. Thanks for clarifying that for me!

LN
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top