I believe (or at least this is how I understand it) that the point of the exercise is SoC. The 'wrapper' causes a separate function to execute every time an element inside of the array is accessed and this function is defined somewhere else (not inside the while loop). Your code could work in case it would have used a reference array instead. But I think you mean with 'expensive' you mean using the tie?
Anyways, if you would use an array reference your code does work:
use lib '.' ;
use strict ;
use warnings ;
use ar ;
my @ar ;
my $ar2 = tie @ar, "ar" ;
@ar = (1, 2, 3) ;
sub make_list_iterator {
my $list = $_[0] ;
return sub {
return () if !@{$list};
return shift(@{$list});
};
}
my $iter = make_list_iterator(\@ar) ;
while ( my ($item) = $iter->() ) {
print "$item\n" ;
}
I'm not showing how to implement ar, plenty of examples in previous posts