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

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.