in reply to Re: Re: Inserting into an array while stepping through it
in thread Inserting into an array while stepping through it
Don't you think you should explain that a bit?
Hrm. Well, I guess I didn't think I should, but you've made me question that. ;-) It's pretty straight forward, I think. And it wouldn't take much experimentation to see what is going on, even if someone couldn't tell immediately.
But, I don't mind...
I wrote the loop as 0 .. $#array and, as a style issue, I don't really like that. I think it would be clearer to say 1 .. @array but, as I don't use $_ at all it doesn't much matter. It will execute the body of the loop as many times as there are elements in @array when the loop starts. That last is important because we may change the size of the array inside the loop but that won't change how many times we loop.
Inside the loop, I use shift to remove an element from the front of the array. Then I get ready to push something back onto the end of the array. What we push is determined by whether our element meets a condition. If it does, I call my_sub() and the return value of my_sub() gets pushed onto the array. If it doesn't match the condition, then I push the element itself back onto the array. When the loop is done, we've processed each element in the original array exactly once.
There is one other important thing to notice. The subroutine, my_sub(), could return more than one value. That's fine. The push builtin takes an array as its first argument and a list of additional arguments and pushes all of the additional arguments onto the array. That's how the array can grow. Also, since push takes a list, the subroutine will execute in list context. That might be necessary for it to know that it should return a list.
I think that about explains it... any questions?
-sauoq "My two cents aren't worth a dime.";
|
|---|