use strict; use warnings; sub makeClosure { my %pos; # hash that will store the positions of all the arrays return sub { my $array = shift; $pos{$array} //= -1; # To avoid "Use of uninitialized value" $pos{$array} = (($pos{$array})+1) % @$array; return $array->[$pos{$array}]; } } my $sub = makeClosure; my $array1 =[1..4]; my $array2 = ['a'..'c']; $\ = $/; print $sub->($array1) for 1..3; print $sub->($array2) for 1..2; print $sub->($array1) for 1..3; print $sub->($array2) for 1..2; print "__________"; print "Unblessed reference : ", $array2; *cycle = $sub; # &main::cycle is now our closure use subs 'cycle'; # Tell Perl that there is a function called cycle, because there was no 'sub cycle'. # This is only useful if you want to call cycle without parenthesis bless $array2; # $array2 is now an object of class 'main' print "Blessed reference : ", $array2; print cycle $array2; # this works because of use subs print $array2->cycle() for 1..3; # calls main::cycle on object $array2 sub cycle2(+) { my $array = shift; $sub->($array); } print "__________"; print cycle2 $array1; my @array = qw/Tic Tac/; print cycle2 @array for 1..4; #### 1 2 3 a b 4 1 2 c a __________ Unblessed reference : ARRAY(0x10eb6a0) Blessed reference : main=ARRAY(0x10eb6a0) a b c a __________ 3 Tic Tac Tic Tac