in reply to Caller, caller, wherefore art thou, caller?

"I'll just mark my position with caller and if each() isn't called from the same spot, automatically reset the index."

Not addressing the question directly - but I'd not like this behaviour even if you could do it. Consider the case when you go back to the same location without having accessed the hash in between. Would it really make sense for it to carry on from the same position?

Personally I'd abstract out a separate iterator so you would do something like:

my $array = Array::AsHash->new({array => \@array}); { my $next_key_value = $array->each; while ( my ($key, $value) = $next_key_value->() ) { print "$key : $value\n"; last if some_condition($key, $value); } }

Replies are listed 'Best First'.
Re^2: Caller, caller, wherefore art thou, caller?
by Aristotle (Chancellor) on Oct 10, 2005 at 20:52 UTC

    Of course the current implementation already is an iterator – if you need several, you can just instantiate any number of Array::AsHash objects on the same underlying array.

    If Ovid prefers this, he could facilitate it by providing a ->copy constructor which resets the iterator in the new instance, for use by code which has no access to the original underlying array.

    However, assuming the class does not contain more methods, I wonder why an object is at all necessary for this. I’d just bake closure directly:

    my $each = make_array_iterator \@array; while( my( $idx, $val ) = $each->() ) { # ... }

    That seems far more natural to me.

    Makeshifts last the longest.

      Of course the current implementation already is an iterator – if you need several, you can just instantiate any number of Array::AsHash objects on the same underlying array.

      True, but when Ovid said (my emphasis):

      I'm working on some code which lets me do, amongst other things

      I assumed that iterators were only one part of what he wanted Array::AsHash to do, so it still might make good sense to abstract out the iterator part.