Array::Iterator(3pm)

Ok bestie, you're reading the Array::Iterator(3pm) man page, and it's literally the blueprint for iterating over Perl arrays with style. No cap, this module is iconic. Let's get into it. ๐Ÿ’…


๐ŸŒธ NAME ๐ŸŒธ

Array::Iterator - A simple class for iterating over Perl arrays

๐Ÿ’ซ VERSION ๐Ÿ’ซ

Version 0.136

โœจ SYNOPSIS โœจ

Okay so Array::Iterator is a Perl module that gives you a super simple, one-way (uni-directional, if we're being fancy) iterator for walking through arrays. It works with plain arrays, array refs, or even a hash ref that has an array inside. You get methods like next, has_next, peek, and current so you can control exactly how you access each element. It keeps an internal pointer so you go through elements one by one without messing up the original array. It's a clean, object-oriented vibe, inspired by Java's Iterator interface. And yes, you can subclass it for your own custom behavior. ๐Ÿ’–

use Array::Iterator;

# create an iterator with an array
my $i = Array::Iterator->new(1 .. 100);

# create an iterator with an array reference
my $i = Array::Iterator->new(\@array);

# create an iterator with a hash reference
my $i = Array::Iterator->new({ __array__ => \@array });

# a base iterator example
while ($i->has_next()) {
    if ($i->peek() < 50) {
        # ... do something because
        # the next element is over 50
    }
    my $current = $i->next();
    # ... do something with current
}

# shortcut style
my @accumulation;
push @accumulation => { item => $iterator->next() } while $iterator->has_next();

# C++ ish style iterator
for (my $i = Array::Iterator->new(@array); $i->has_next(); $i->next()) {
  my $current = $i->current();
  # .. do something with current
}

# common perl iterator idiom
my $current;
while ($current = $i->get_next()) {
  # ... do something with $current
}

Bestie, please don't change the array while you're iterating over it. There's no enforcement right now (the author says they will if they find an efficient way), but it's not recommended. This class is just here to give you a clear, simple way to do generic iteration, nothing extra (yet). ๐Ÿซถ


๐ŸŽ€ new (@array | $array_ref | $hash_ref) ๐ŸŽ€

The constructor can take a plain Perl array, an array reference, or a hash reference that has the array under a single key called __array__. Here's the tea: single-element arrays are not supported by the first two calling conventions. Why? Because you can't tell the difference between an array with one element that happens to be an array ref, and an array ref with one element. So previous versions of the constructor would throw an exception. If you need to pass an array that might have only one element, just wrap it in a hash ref with the key __array__, like this:

my $i = Array::Iterator->new({ __array__ => \@array });

๐Ÿ”ฎ _current_index ๐Ÿ”ฎ

This is an lvalue-ed subroutine (fancy, right?) that lets you access the iterator's internal pointer. Subclasses can use it to get at the value.

๐ŸŒŸ _iteratee ๐ŸŒŸ

This returns the item being iterated over โ€” in our case, an array.

๐Ÿ’Ž _get_item ($iteratee, $index) ๐Ÿ’Ž

This method is used by all the other routines to access items. Give it the iteratee and an index, and it returns the item stored in $iteratee at the index $index.

๐Ÿ’– iterated ๐Ÿ’–

Gives you access to the _iterated status, for subclasses.

โœจ has_next([$n]) โœจ

This method returns a boolean: true (1) if there are still more elements in the iterator, false (0) if there aren't. You can optionally pass a positive integer (> 0) to check for an element at a specific position. Think of it like an ordinal number:

$i->has_next(2);  # 2nd next element
$i->has_next(10); # 10th next element

Note that has_next(1) is exactly the same as has_next().

Throws an exception if $n <= 0.

๐ŸŒธ hasNext ๐ŸŒธ

Alternative name for has_next.

๐Ÿ’… next ๐Ÿ’…

Returns the next item in the iterator. Only call this once per iteration because it advances the index pointer to the next item. If you call it after all elements have been exhausted, it throws an exception.

๐Ÿฆ‹ get_next ๐Ÿฆ‹

Returns the next item in the iterator. Only call this once per iteration because it advances the index pointer to the next item. If you call it after all elements have been exhausted, it returns undef. This method exists to support a super common Perl iterator idiom:

my $current;
while ($current = $i->get_next()) {
    ...
}

In this idiom, the loop stops once $current is assigned a false value. The only problem is that it doesn't play nice with undefined or false values inside the iterator. If that fits your data, great! Otherwise, the author recommends using the has_next/next idiom instead.

๐Ÿ“ getNext ๐Ÿ“

Alternative name for get_next.

๐Ÿ‘‘ peek([$n]) ๐Ÿ‘‘

You can use this to peek ahead at the next item in the iterator. It's non-destructive, meaning it does not advance the internal pointer. If you try to peek beyond the bounds of the iterator, it returns undef. You can optionally pass a positive integer (> 0) to specify how far ahead you want to peek:

$i->peek(2);  # gives you 2nd next element
$i->peek(10); # gives you 10th next element

Note that peek(1) is the same as peek(). Throws an exception if $n <= 0.

NOTE: Before version 0.03, this method would throw an exception if called out of bounds. The author decided that wasn't good practice because it made it hard to peek ahead effectively. Now it doesn't. But calling with an argument that is <= 0 still throws an exception, because that's clearly a sign of incorrect usage. ๐Ÿ’€

๐ŸŒˆ current ๐ŸŒˆ

This gets the current item in the iterator. It's non-destructive, so it doesn't advance the internal pointer. The value will match the last value dispensed by next or get_next.

๐Ÿงš current_index ๐Ÿงš

This gets the current index in the iterator. Non-destructive, so it doesn't advance the internal pointer. The value will match the index of the last value dispensed by next or get_next.

๐Ÿ’œ currentIndex ๐Ÿ’œ

Alternative name for current_index.

๐Ÿ”ฅ reset ๐Ÿ”ฅ

Reset the index to allow iteration from the start.

โญ get_length โญ

A basic accessor that returns the length of the array being iterated over โ€” i.e., the number of elements in the array.

๐ŸŽ€ getLength ๐ŸŽ€

Alternative name for get_length.


๐Ÿ”ฎ TODO ๐Ÿ”ฎ

  • Improve BiDirectional Test suite โ€” I want to test the back-and-forth a little more and make sure they work well with one another.
  • Other Iterators โ€” Array::Iterator::BiDirectional::Circular, Array::Iterator::Skipable and Array::Iterator::BiDirectional::Skipable are just a few ideas I have had. I am going to hold off for now until I am sure they are actually useful.

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

This module now includes several subclasses of Array::Iterator which add certain behaviors to Array::Iterator, they are:

  • Array::Iterator::BiDirectional โ€” Adds the ability to move backward and forward through the array.
  • Array::Iterator::Circular โ€” When this iterator reaches the end of its list, it will loop back to the start again.
  • Array::Iterator::Reusable โ€” This iterator can be reset to its beginning and used again.

The Design Patterns book by the Gang of Four, specifically the Iterator pattern.

Some of the interface for this class is based on the Java Iterator interface.


๐ŸŒˆ OTHER ITERATOR MODULES ๐ŸŒˆ

There are several on CPAN with the word Iterator in them. Most of them are actually iterators included inside other modules, and only really useful within that parent module's context. There are, however, some other modules out there that are just for pure iteration. I have provided a list below of the ones I have found if perhaps you don't happen to like the way I do it.

  • Tie::Array::Iterable โ€” This module ties the array, something we do not do. But it also makes an attempt to account for, and allow the array to be changed during iteration. It accomplishes this control because the underlying array is tied. As we all know, tie-ing things can be a performance issue, but if you need what this module provides, then it will likely be an acceptable compromise. Array::Iterator makes no attempt to deal with this mid-iteration manipulation problem. In fact, it is recommended to not alter your array with Array::Iterator, and if possible we will enforce this in later versions.
  • Data::Iter โ€” This module allows for simple iteration over both hashes and arrays. It does it by importing several functions that can be used to loop over either type (hash or array) in the same way. It is an interesting module, it differs from Array::Iterator in paradigm (Array::Iterator is more OO) and intent.
  • Class::Iterator โ€” This is essentially a wrapper around a closure-based iterator. This method can be very flexible, but at times is difficult to manage due to the inherent complexity of using closures. I actually was a closure-as-iterator fan for a while but eventually moved away from it in favor of the more plain vanilla means of iteration, like that found Array::Iterator.
  • Class::Iter โ€” This is part of the Class::Visitor module and is a Visitor and Iterator extension to Class::Template. Array::Iterator is a standalone module that is not associated with others.
  • Data::Iterator::EasyObj โ€” Data::Iterator::EasyObj makes your array of arrays into iterator objects. It also can further nest additional data structures including Data::Iterator::EasyObj objects. Array::Iterator is one-dimensional only and does not attempt to do many of the more advanced features of this module.

๐Ÿ™ ACKNOWLEDGEMENTS ๐Ÿ™

Thanks to Hugo Cornelis for pointing out a bug in peek().

Thanks to Phillip Moore for providing the patch to allow single element iteration through the hash-ref constructor parameter.


๐Ÿ‘‘ MAINTAINER ๐Ÿ‘‘

Nigel Horne, <njh at nigelhorne.com>

2025-2026


๐ŸŒŸ ORIGINAL AUTHOR ๐ŸŒŸ

stevan little, <stevan@iinteractive.com>


Copyright 2004, 2005 by Infinity Interactive, Inc.

<http://www.iinteractive.com>

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


๐Ÿ•ฐ๏ธ PREVIOUS MAINTAINER ๐Ÿ•ฐ๏ธ

Maintained 2017 to 2025 PERLANCAR

๐Ÿซถ SUPPORT ๐Ÿซถ

okay bestie, real talk for a sec ๐Ÿ’– this module is handed to you as-is, with no warranty of any kind. That's it, that's the deal. No promises, no pinky swears, no "it'll def work on your weird box." ๐Ÿ’€

But if you do find a bug, or you're sitting there like "hmm, wouldn't it be iconic if this did X" โ€” please tell someone!! ๐Ÿ™ Report bugs or feature requests to bug-array-iterator at rt.cpan.org, or slide into the RT web interface at:

http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Array-Iterator

The maintainer gets notified, and then you get notified automatically as progress happens on your bug while changes get made. It's giving communication, it's giving teamwork, we love a feedback loop โœจ

You can also pull up the docs for this module straight from your terminal with perldoc:

perldoc Array::Iterator

And here's the little link farm of places you can go hunting for info, no cap ๐ŸŒˆ


๐Ÿ˜ญ POD ERRORS ๐Ÿ˜ญ

Hey! The above document had some coding errors, which are explained below. (Not me being messy, it's literally what it says ๐Ÿ’…)

Around line 24:

Non-ASCII character seen before =encoding in 'Java's'. Assuming UTF-8

Like, the fancy apostrophe in Java's showed up before any =encoding declaration was made, so it just assumed UTF-8 and moved on with its life. We've all been there ๐Ÿ™ˆ


and that's a wrap on the whole page, bestie!! ๐ŸŽ€ you just read Array::Iterator(3pm), served up by the Perl docs peeps, version v5.40.1, dated 2026-03-11. go forth and iterate, you absolute main character ๐Ÿ‘‘๐Ÿ’œ

๐Ÿ“ฆ where this page comes from