in reply to Re: Learning Perl - Question About Using a For Loop To Pull Data From an Array
in thread Learning Perl - Question About Using a For Loop To Pull Data From an Array

Thank you for your reply. As you mentioned the script works fine. This is an example from a textbook which is why it may seem odd and not look like a real world script.

I am not having any issues with the code, rather I am trying to understand how the for loop is using the $counter variable to pull out the actual number that user entered when it appears that $counter is being used as a scalar.

For example if the user enters 1 and 3 they get fred and barnet back which are the first and third items in the array respectively.

What is confusing me is why is $names $counter - 1 giving the correct values back. If the user enters 2 values, such as 1 and 3, $counter would = 2, not 1 or 3 since it is being treated as a scalar. Yet the script correctly returns the 1st and 3rd item in the array instead of the the 1st and 2nd item of the array.

Thank you for your help.

  • Comment on Re^2: Learning Perl - Question About Using a For Loop To Pull Data From an Array

Replies are listed 'Best First'.
Re^3: Learning Perl - Question About Using a For Loop To Pull Data From an Array
by NetWallah (Canon) on Apr 01, 2016 at 18:44 UTC
    It seems that the name chosen, $counter, is confusing you.

    It is being used as an INDEX, rather than as a traditional COUNTER.

    The array is indexed from 0 to (n-1). (Updated to n-1)(Thanks, Corion)

    You need to subtract one from the value entered, in order to get the equivalent index for a zero-based array.

    Hopefully, that clarifies things.

    FYI, Fred's friend is named Barney, not barnet. and Barney's kid is Bamm-Bamm.

            This is not an optical illusion, it just looks like one.

Re^3: Learning Perl - Question About Using a For Loop To Pull Data From an Array
by Marshall (Canon) on Apr 01, 2016 at 20:33 UTC
    What this foreach $counter (@userNumber){} does is assign $counter to each value in the array @userNumber. It does this on a first in, first out basis. If the user entered say 1,3,2.. The first loop $counter = 1, then $counter =3, then on last loop, $counter = 2. Before print "\nthe name is: $names[$counter - 1], add a statement, print "counter = $counter\n";. And you can see what counter is. Use some non-sequential test cases.

    Part of the problem here is a rather poor choice of names for "counter". $name_number or something similar would have been better. There is no "count" function of $counter! It is being used as a 1 based index to the names array. Perl starts arrays at 0, not one, so that is what $counter-1 is all about. Hopefully that makes sense?