use Iterator; my $i = 0; my $iterator = new Iterator(sub { return ++$i }); print "Before calling anything: $i\n"; print "First call yields: ", $iterator->value, "\n"; print "After first call: $i\n"; #### Before calling anything: 0 First call yields: 1 After first call: 1 #### Before calling anything: 1 First call yields: 1 After first call: 2 #### use Iterator; my $i = 0; sub get_a { return new Iterator(sub { print "a called\n"; return $i++ }); } sub get_b { my $a = get_a; return new Iterator(sub { print "b called\n"; return $a->value }); } print "Now I will get_b ($i):\n"; $b = get_b; print "Got b ($i)\n"; print "First value is ($i):\n"; print "b: ", $b->value, " ($i)\n"; #### Now I will get_b (0): Got b (0) First value is (0): b called a called b: 0 (1) #### Now I will get_b (0): a called b called a called Got b (2) First value is (2): b called a called b: 0 (3)