package Array::AsHash; use warnings; use strict; use Class::Std; { my ( %array_for, %last_each_from, %current_index_for ) : ATTRS; sub BUILD { my ( $class, $ident, $arg_ref ) = @_; my $array = $arg_ref->{array} || []; $array_for{$ident} = $array; } sub each { my $self = shift; my $ident = ident $self; my $index = $current_index_for{$ident} || 0; my $caller = join '', caller; if ( ( $last_each_from{$ident} || '' ) ne $caller ) { # calling from a different line. Reset the index and caller $index = $current_index_for{$ident} = 0; $last_each_from{$ident} = $caller; } my @array = @{ $array_for{$ident} }; if ( $index >= @array ) { $current_index_for{$ident} = 0; return; } my ( $key, $value ) = @array[ $index, $index + 1 ]; $current_index_for{$ident} += 2; return ( $key, $value ); } } 1;