http://www.perlmonks.org?node_id=1043484


in reply to Re^5: foreach argument modification inside loop, followed by return from loop
in thread foreach argument modification inside loop, followed by return from loop

As far as I can tell, you only ever look at the first element of the jobs array;
No, first job can return 'wait' and loop will jump next job after this line
return 'wait' unless --$maxcnt;
not to mention getting rid of any need to flirt with array modification inside a loop
but it might not stay that way if your logic changes in the future (it does create a bit of a trap for the unwary)

Well, it's unlikelly going to change the way that loop will continue after do_finish(). My do_finish() sub is something that called before finish.

Also, let's imagine that I copied my @{$self->{jobs_a}} to temporary variable @tmp_jobs. Will it solve the problem? No. If I change the code so loop continues after do_finish(), it will still introduce the bug (however a bit more visible).

I think unit tests with 100% branch coverage would be a solution here. (+ effort to keep it 100% after any modifications)

Let me/us know which way you end up going
I don't know yet. Certainly, there are ways to make it bit better. But I actually think it's irrelevant to this topic :)
  • Comment on Re^6: foreach argument modification inside loop, followed by return from loop
  • Download Code

Replies are listed 'Best First'.
Re^7: foreach argument modification inside loop, followed by return from loop
by rjt (Curate) on Jul 10, 2013 at 22:13 UTC
    As far as I can tell, you only ever look at the first element of the jobs array;

    No, first job can return 'wait' and loop will jump next job after this line

    return 'wait' unless --$maxcnt;

    I see you're correct; as I mentioned, I only had time for a brief look so I could offer up some (illustrative) feedback on how you might approach your question of "Problem that I mentioned in my posting, followed by return from loop that "for" loop is in get_task(). i.e. there is another outer "for" loop.".

    In any case, if you like, you can still use similar logic by shifting in a while loop, since you consume the element every time, and the shift of course doesn't care about changes from one loop iteration to the next.

    Certainly, there are ways to make it bit better. But I actually think it's irrelevant to this topic :)

    Ah, perhaps I've over-stayed my helpfulness. :-) Good luck! :-)