Like this:

Related

Is there any reason to take a loop iterator out of the loop by default ?

I don’t understand very well this change, I think that makes more sense to “add code” those who want a loop iterator outside the loop, better than to make “add code” for those who reuse semantically the same iterator in loops.

So now 5.12 has further extended the awkward action-at-a-distance misfit of ‘each’ to operate on more containers than it used to on 5.10. I can see this being abused far more often, creating lots more bugs where the globalness of it accidentally leaks out, than I can see cases for it being useful.

foreach my $idx ( 0 .. $#arr ) { my $elem = $arr[$idx] } is already neat enough. If you actually wanted to preserve the index from one loop to the next; just remove that ‘my’ start using a C-style for() loop.

each is useful on hashes because you can’t just do that with $key; there is no obvious $key++ operation to walk to the “next” key.

Actually I think its quite a useful addition and I much prefer its succinctness over the alternatives. However its good to be wary and I for one would do my best avoid any self abuse it may cause using it 🙂

BTW… using an iterator is my preferred solution. For eg. Array::Iterator mentioned in another answer in that stackoverflow question is something I would recommend.

About…..

My name is Barry Walsh. I'm a freelance IT consultant from London, UK. [more]

This blog is mostly about Perl programming because this is what I use and love (and occasionally hate!) for the majority of my working (and sometimes non-working) day.

Occasionally I will touch on other subjects like PostgreSQL, Mac OSX, UNIX, Linux, Ruby, jQuery, Javascript, XML and many more techie things that I also play with regularly. Other non techie aspects of my life may slip in now and again but I'll try and keep that to a minimum because its normally boring anyway :)