Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: Using an array element as a loop iterator

by 2teez (Priest)
on Nov 07, 2013 at 19:46 UTC ( #1061615=note: print w/replies, xml ) Need Help??

in reply to Using an array element as a loop iterator

Hi gurpreetsingh13,
if I understand want you want done, is to use the index of one array for another, printing out the value in the other one.
First of, I will say use a better variable name instead of a and b like you did.
Secondly, like other monks rightly pointed out, though you have an array variable @a but it contains an arrayref check perlref
That not withstanding you can get what you want done simply by dereferencing the arrayref and loop through using the index to print the corresponding values in the second array like thus:

use warnings; use strict; my @array1 = [ 1, 2, 3 ]; my @array2 = ( 2, 4, 6, 7 ); for ( 0 .. $#{ $array1[0] } ) { print $array2[$_], $/; } ## OR print join $/ => @array2[ 0 .. $#{ $array1[0] } ];
Of course, the answer you get is 2,4 and 6. Atleast that is what you have using the OP as showed by using the C-style for loop, which you supposed worked and indeed it worked since it gave you your desired result,
BUT did you check your "@a" variable after that to see it values? Please do and see what you have!
Using Data::Dumper

If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1061615]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2018-01-23 22:29 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (254 votes). Check out past polls.