技術雜談:Iterator and Generator in Perl

PUBLISHED ON NOV 12, 2014

    To generate a list of numbers, Perl provides the syntax .. (double dots). However, the syntax only provides ascending sequences with 1 increment. What can we do if we need more flexible sequences in Perl?

    In the following example, you can see that .. only generate an ascending sequence.

    # print out 1 2 3 ... 10
    $ perl -le '$, = " "; print (1..10);'
    
    # print out nothing
    $ perl -le '$, = " "; print (10..1);'

    If you need more flexible iterators or generators, you may check out List::Gen module. This module provides higher order functions, list comprehensions, generators, iterators, and other utility functions.

    For example, function range generates a generator that can be used in loop.

    use feature qw(say);
    use List::Gen qw(range);
    
    # generate 10, 8, 6, 4, 2
    my $range = range(10, 1, -2);
    
    for my $i (@{$range}) {
        # do something
    }

    There are still functions worth exploring. You may check the page of List::Gen to find useful functions.