blakem has asked for the wisdom of the Perl Monks concerning the following question:
This is my first attempt in using a closure as an itterator.
I noticed that I had several scripts
with cut-n-pasted code for deciding which lines in
a datafile to process. I'm trying to consolidate
that logic by using an itterator/closure
instead. It seems to work just fine, but since I'm breaking new ground (for me, at least) I thought I'd ask for a little peer review.
Thanks.
Thanks.
And its used as such:package My::Package; my $datafile = '/path/to/data.txt'; # each line in file has a numbered key ($key) followed by # some data. file is sorted based on incrementing keys sub itter_maker { # return a function that passes back # data only from lines with keys between # $min and $max my $min = shift; my $max = shift; my $done; my $fh = new IO::File "$datafile"; return( sub { return if $done; my (@data,$row,$key); while (1) { chomp($row = <$fh>) or last; #### # [SNIPPED] munge $row, set $key and @data #### next if $key < $min; $done = 1 && return if ($key > $max); last; } return ($key,\@data); }); }
#!/usr/bin/perl use My::Package; # only loop through lines with "30 <= $key <= 70" my $nextrow = itter_maker(30,70); while (my ($num,$dataref) = $nextrow->()) { ### do stuff }
|
---|
Replies are listed 'Best First'. | |
---|---|
(jeffa) Re: Closures as Itterators
by jeffa (Bishop) on Jun 30, 2001 at 19:50 UTC | |
by blakem (Monsignor) on Jul 01, 2001 at 14:38 UTC | |
by dragonchild (Archbishop) on Jul 02, 2001 at 21:33 UTC | |
by blakem (Monsignor) on Jul 02, 2001 at 22:48 UTC | |
by dragonchild (Archbishop) on Jul 02, 2001 at 23:30 UTC | |
| |
Re: Closures as Itterators
by bikeNomad (Priest) on Jun 30, 2001 at 20:19 UTC | |
by tye (Sage) on Jun 30, 2001 at 21:27 UTC |
Back to
Seekers of Perl Wisdom