aUserName has asked for the wisdom of the Perl Monks concerning the following question:
At the end of this post is a simple script I wrote which was from one of the exercises in the learning perl book.
Basically there is an array with names in it, the user enters numbers, and once they hit crtl D (EoF) the script returns the corresponding value in the array.
I.e., if the array has fred betty barnet dino wilma pebbles bam-bam as values and the user enters 1 and 3, they should get fred and barnet back.
My code works, but I do not know why. In the foreach loop, I created $coutner (@userNumber) which means that if the user entered two numbers, $counter would = 2 and the loop would run twice.
The next line says to print $names $counter - 1
This works fine, the user is correctly given the name for the corresponding number they enter.
So if the user enters 1 and 3 they get fred and barnet back.
What is confusing me is why is $names $counter - 1 giving the correct entry. If the user enters 2 values, such as 1 and 3, $counter would = 2, not 1 or 3.
I verified this to be true by using print $counter and the end of the script during some of my tests.
Yet, when print $names $counter -1 is used and the user enters 1 and 3, fred and barnet are returned even though $counter = 2, not 1 or 3.
I would think that instead, since $counter = 2, the user would get fred and betty back, not fred and barnet.
Can anyone explain what I am missing?
#! perl ############ This script takes the number a user entered and returns t +he corrseponding name. ##### Create the list of names @names = qw / fred betty barnet dino wilma pebbles bam-bam /; ### # test to make sure @names is define correctly # # print @names; ### ###### Greet user and get the number from the user. print "\nWelcome to the name program.\nPlease enter a number or number +s and hit crtl + D when done: "; @userNumber = <STDIN>; ### test to dump array # # print @userNumber; ### ### test to see what $counter would be when used in foreach loop #$counter = @userNumber; #print $counter; ### ###### Return a name based on the number provided. foreach $counter (@userNumber) { print "\nthe name is: $names[$counter - 1] "; }
|
|---|