NAME
Mojo::Collection::Role::Iterable - Iterator capabilities as a composable role for Mojo::Collection
SYNOPSIS
use Mojo::Collection;
my $c = Mojo::Collection->with_roles('+Iterable')->new(qw(foo bar baz));
# Sequential iteration
while (defined(my $item = $c->iterate)) {
say $item;
}
# Cursor movement
$c->reset;
say $c->curr; # foo
$c->increment;
say $c->curr; # bar
say $c->next; # baz
say $c->prev; # foo
# Rewind and go again
$c->reset;
DESCRIPTION
Mojo::Collection::Role::Iterable is a Mojo::Role for iterator-style cursor access in Mojo::Collection.
METHODS
curr / current / item
my $thing = $c->curr;
Returns the element at the current cursor position.
prev
my $thing = $c->prev;
Returns the element before the cursor, or undef at the beginning.
next
my $thing = $c->next;
Returns the element after the cursor, or undef at the end.
increment
$c->increment; # chainable
Moves the cursor forward by one (no-op at the last element).
decrement
$c->decrement; # chainable
Moves the cursor backward by one (no-op at the first element).
reset
$c->reset; # chainable
Rewinds both the cursor and the iterate position to 0.
iterate
while (defined(my $item = $c->iterate)) { ... }
Returns the item at the current iteration position and advances it, keeping the cursor in sync. Returns undef when exhausted. Call reset to iterate again.
CAVEAT
The safe iteration idiom is:
while (my ($item) = $c->iterate) { ... }
Note the parentheses around $item — this is a list assignment, not a scalar one. The loop terminates only when iterate returns an empty list, which happens exclusively when the collection is exhausted. This means the loop handles false values (0, "", "0") and even undef as legitimate collection items without terminating early.
The simpler forms are tempting but have failure modes:
while (my $item = $c->iterate) { ... } # terminates early on 0, "", undef
while (defined(my $item = $c->iterate)) { ... } # terminates early on undef
Use these only if you can guarantee your collection contains no false or undef values respectively. When in doubt, use the list form.
OVERLOADING
This role installs two operator overloads:
++-
Calls
increment, moving the cursor forward by one. The collection contents are not affected; only the cursor position changes. ---
Calls
decrement, moving the cursor backward by one. Same caveat applies.
SEE ALSO
Mojo::Collection, Mojo::Base, Hash::Util::FieldHash
AUTHOR
Simone Cesano <scesano@cpan.org>
COPYRIGHT AND LICENSE
Copyright (C) Simone Cesano.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.