I have lines of code with two large arrays (so can't just write it into a hash) which I want to connect with a hash.
For example, $array1[0]
becomes the key and $array2[0]
becomes the value and so on to $array1[150]
,$array2[150]
.
Any ideas how I do this?
martin clayton has the best answer for your general question, put there's also an interesting new feature in Perl 5.12. You can use each on an array so you can easily iterate through parallel arrays. It's useful when you want to manipulate the values before you use them:
(I tried posting this as a comment to brian's answer, but couldn't get the formatting right.)
You have to be careful to avoid nested uses of
each
.each
works on a "global" iterator on the array. When it reaches the end, it returns false and then resets the position to the beginning. Thus following code results in an infinite loop.Thanks to RJBS for his talk at YAPC::NA where he pointed out the global nature of the built-in iterator.
You can do it in a single assignment:
It's a common idiom. From perldoc perldata on slices:
When I see one of these I see a mental image of a zipper...