I’m trying to create an array of hashes, but I’m having trouble looping through the array. I have tried this code, but it does not work:
for ($i = 0; $i<@pattern; $i++){
while(($k, $v)= each $pattern[$i]){
debug(" $k: $v");
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First, why aren’t you
useingstrictandwarnings? The following lines should be at the top of every Perl program you create, right after#!/usr/bin/perl. Always.And I know you aren’t because I’m pretty sure you’d get some nice error messages out of
strictandwarningsfrom this, and from many other places in your code as well, judging by your variable use.Second, why aren’t you doing this:
That loops through every element in
@pattern, assigning them to$ione at a time. Then, in your loop, when you want a particular element, just use$i. Changes to$iwill be reflected in@pattern, and when the loop exits,$iwill fall out of scope, essentially cleaning up after itself.Third, for the love of Larry Wall, please declare your variables with
myto localize them. It’s really not that hard, and it makes you a better person, I promise.Fourth, and last, your array stores references to hashes, not hashes. If they stored hashes, your code would be wrong because hashes start with
%, not$. As it is, references (of any kind) are scalar values, and thus start with$. So we need to dereference them to get hashes:Or, your way: