![]() Using what we've already seen, we could compare the guess repeatedly against a series of good answers stored in separate scalar variables. Let's see how we can modify this program to allow more than one valid secret word. But, we weren't trying to write a security system, just an example for this book. Of course, this program is not very secure, because anyone who is tired of guessing can merely interrupt the program and get back to the prompt, or even look at the source to determine the word. The result of the comparison controls a while loop, which executes the block as long as the comparison is true. The guess is compared with the secret word using the ne operator, which returns true if the strings are not equal ( ne is the logical opposite of the eq operator). After the greeting, the (non-Erik) person is asked (with another print) for the guess. What is the secret word? " įirst, we define the secret word by putting it into another scalar variable, $secretword. Print "Hello, $name!\n" # ordinary greeting Print "Hello, Erik! How good of you to be here!\n" First the program, and then an explanation: $secretword = "gecko" # the secret word For everyone except Erik, we'll have the program repeatedly ask for guesses until the person guesses properly. Well, now that we have the name, let's have the person running the program guess a secret word. Putting it all together, we get: print "What is your name? " Now, all we need to do is say Hello, followed by the value of the $name variable, which we can do by embedding the variable inside the quoted string: print "Hello, $name!\n" To get rid of the newline, we use the chomp() function, which takes a scalar variable as its sole argument and removes the trailing newline, if present, from the string: chomp $name The value of $name at this point has a terminating newline ( Erik comes in as Erik\n). This gives us the following program: print "What is your name? " We assign this input to the $name variable. And the way to get a line from the terminal is with the construct, which (as we're using it here) grabs one line of input. The previous program showed us how to prompt: use the print function. To do that, we need a way to prompt and a way to accept input. For now, assume that you can hold a single number or string (sequence of characters) in a scalar variable. In Chapter 2, Scalar Data, we'll go into more detail about what these variables can hold, and what you can do with them. For this program, we'll use the scalar variable $name to hold your name. One kind of place to hold values (like a name) is a scalar variable. To do this, we need a place to hold the name, a way to ask for the name, and a way to get a response. Let's have the program call you by your name. The Hello, world greeting is a touch cold and inflexible. 1.6.2 Asking Questions and Remembering the Result ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |