Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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

by tangent (Vicar)
on Apr 01, 2016 at 22:06 UTC ( #1159341=note: print w/replies, xml ) Need Help??

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

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"; }
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

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1159341]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (2)
As of 2022-05-17 17:08 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (68 votes). Check out past polls.