Anno Siegel (
[email protected]) wrote:
: > Anno Siegel (
[email protected]) wrote on MMMDCCV September
: > MCMXCIII in <URL:: > () >
: > () >
: > () > Nah, a hypothetical 'each' for arrays would be:
: > () >
: > () > while (my ($key, $value) = each @array) {
: > () > # $key is the index, $value the value.
: > () > }
: > ()
: > () That would be my idea too of what "each" should mean for an array.
: > () However, there are other interpretations. Besides Malcolm's (essentially
: > () equivalent to "foreach"), there was
: > ()
: > () while (my ($key, $value) = each @array) {
: > () # $key is an even-indexed element, $value an odd-indexed element
: > () }
: > ()
: > () which is also a plausible generalization of the behavior of "each",
: > () though, I believe, not a very useful one.
: > ()
: > () Maybe this ambiguity is another reason why "each" hasn't been generalized.
: >
: >
: > My guess the reason 'each' hasn't been generalized is that arrays don't
: > have slots to keep the state of the iterator. Hashes have them. Adding
: > them to arrays means adding an extra integer to all AVs. Considering that
: > 'each @array' will be used far less than 'each %hash', the price is not
: > worth paying.
: Having the iterator incorporated in the hash itself isn't ideal -- it's
: the reason why we can't nest "each"- and "keys"-loops over the same hash.
: One could also take the opportunity and implement both iterators differently.
: Not bloody likely, I know. I wonder how Perl 6 will behave in that respect.
perl 6, no idea, but the way other languages handle it would be to create
an iteration object, so you could imagine
my $iter1 = iterator_for %hash;
while ( my ($k,$v) = $iter->next ) or such like
OR
store a context handle or other identifier as an optional argument to the
each
while ( my ($k,$v) = each(%hash,$iter1) )