use strict; use warnings; sub lazy_ham { my ($how_many) = @_; my @output_stream = (1); my @streams = map { my $base = $_; # All your base are belong to us my $index = 0; sub { if (@_) { return $base * $output_stream[$index]; } else { return $base * $output_stream[$index++]; } } } (2, 3, 5); for (1..$how_many) { # Find the lowest next item in the available streams my ($lowest) = sort {$a <=> $b} map {$_->('peek')} @streams; $_->('peek') == $lowest and $_->() for @streams; push(@output_stream, $lowest); } shift @output_stream; # Get rid of the seed 1 @output_stream; } print join(', ', lazy_ham(1000)), "\n";