Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

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

by tangent (Parson)
on Apr 01, 2016 at 22:06 UTC ( [id://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"; }
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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-04-18 06:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found