my $array = Array::AsHash->new({array => \@array});
while (my ($key, $value) = $array->each) {
print "$key : $value\n";
}
####
while (my ($key, $value) = $array->each) {
last if some_condition($key, $value);
}
####
my $count = 0;
while ( my $line = get_line_no() ) { # Line 2
print "Line $line\n";
last if $count++; # Line 4
}
sub get_line_no { (caller)[2] }
__END__
Line 2
Line 4
####
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;
####
my @array = qw/key value key1 value1 key2 value2/;
use Array::AsHash;
$array = Array::AsHash->new( { array => \@array } );
while (my ($k,$v) = $array->each) {
print "$k : $v\n";
}
__END__
key : value
key : value
key1 : value1
key2 : value2