Thu
13 Jan 2005
4:30 pm
Want Python-style "generators" in Perl? You can always use a closure as a generator. Example:
sub something {
…
my $sth = $dbh->prepare('SELECT * FROM somewhere');
$sth->execute;
…
my $sth = $dbh->prepare('SELECT * FROM somewhere');
$sth->execute;
consume(sub { $sth->fetchrow_arrayref });
}
sub consume {
my($generator) = @_;
while(my @results = $generator->()) {
# process @results
}
}
Closures are the bomb. Of course, this is not a perfect solution. If you just wanted to generate the numbers from 1 to 99, you could pass a closure to generate one number, but it would have to store its state externally. I believe Perl 6 has a yield command that would allow you to do this easily (see a more thorough discussion).
Full Entries RSS