Understanding and Using Iterators - Perl.com

sub gen_fib {
    my ($low, $high) = (1, 0);

    return sub {
        ($low, $high) = ($high, $low + $high);
        return $high;
    };
}

my $fib = gen_fib();
print $fib->(), "\n" for 1 .. 20;

Besides the funny initialization of $low being greater than $high, it also misses 0, which should be the first item returned. Here is one way to handle it:

sub gen_fib {

    my ($low, $high) = (1, 0);

    my $seen_edge;

    return sub {
        return 0 if ! $seen_edge++;
        ($low, $high) = ($high, $low + $high);
        return $high;
    };
}

State Variables Persist As Long As the Iterator

在古早的 Perl 中,iterator (customized iterator / generator) 可以用 closure 機制來實作。

需要 generator 的情況:用少一點記憶體、無窮元素、循環、太大。文中對每個情況都給一個例子。