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.
When $counter is used to access elements in the @names array it is not a static value, it takes on the value of each element in @userNumber in turn. Maybe this helps:
my @names = qw / fred betty barnet dino wilma pebbles bam-bam /;
my $total = scalar @names;
print "number of elements in array: $total\n";
my $first = 0;
print "index number of first element: $first\n";
my $last = $#names;
print "index number of last element: $last\n";
for my $index ( $first .. $last ) {
print "index $index: $names[ $index ]\n";
}
my @userNumber = qw / 1 3 /;
my $counter = @userNumber;
print "counter is: $counter\n";
print "Start loop...\n";
foreach $counter ( @userNumber ) {
print "counter is: $counter\n";
my $index = $counter - 1;
print "\t$counter - 1 = $index: $names[ $index ]\n";
}
OUTPUT:
number of elements in array: 7
index number of first element: 0
index number of last element: 6
index 0: fred
index 1: betty
index 2: barnet
index 3: dino
index 4: wilma
index 5: pebbles
index 6: bam-bam
counter is: 2
Start loop...
counter is: 1
1 - 1 = 0: fred
counter is: 3
3 - 1 = 2: barnet