use strict; use warnings; my @array = qw( this that the other ); # The iterator factory: Call as "my $each = make_each_array( @some_array );" # Use the iterator as "my( $index, $value ) = $each->();" sub make_each_array (\@) { my $aref = shift; my $idx = 0; return sub { my $reset = shift; if( defined $reset ) { die "Subscript ($reset) for each_array reset is out of range 0 .. $#{$aref}" if $reset < 0 || $reset > $#{$aref}; $idx = $reset; return; } if( $idx == @{$aref} ) { $idx = 0; return; } my $current_idx = $idx++; return ( $current_idx, $aref->[$current_idx] ); } } my $each_array = make_each_array( @array ); # A simple while() loop: The most common use case for 'each'. while( my( $idx, $value ) = $each_array->() ) { print "$idx => $value\n"; } # Here 'each' has been reset to zero automatically, just like Perl's each. my ( $idx, $value ) = $each_array->(); print "$idx => $value\n"; # Here we explicitly reset 'each' to zero. $each_array->(0); ( $idx, $value ) = $each_array->(); print "$idx => $value\n"; # Here we explicitly reset 'each' to some non-zero index. $each_array->(3); ( $idx, $value ) = $each_array->(); print "$idx => $value\n";