Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Using an array element as a loop iterator

by 2teez (Vicar)
on Nov 07, 2013 at 19:46 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-04-26 02:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found