No such thing as a small change | |
PerlMonks |
Learning Perl - Question About Using a For Loop To Pull Data From an Arrayby aUserName (Initiate) |
on Apr 01, 2016 at 16:48 UTC ( [id://1159311]=perlquestion: print w/replies, xml ) | Need Help?? |
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?
Back to
Seekers of Perl Wisdom
|
|