Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Limbic Region (3985)

Limbic Region
  (email not shown publicly)
http://gatcomb.org/joshua/perl.html

I love to code perl. If you want to hire me, see details on my homepage.
Thursday September 23, 2004
06:59 PM

Fascination With Iterators

[ #21028 ]
After declaring I was taking a programming hiatus only a few days ago, I have written two pieces of code I am fairly proud of.  The first was an efficient way to process every line in 1 file against every line in another file without slurping the files into memory.

The second was an iterator for x size subsets of y

#!/usr/bin/perl
use strict;
use warnings;

my $iter = combo( 3 , 1 .. 5 );
while ( my @combo = $iter->() ) {
    print "@combo\n";
}

sub combo {
    my $by = shift;
    return sub { () } if ! $by || $by =~ /\D/ || @_ < $by;
    my @list = @_;

    my @position = (0 .. $by - 2, $by - 2);
    my @stop     = @list - $by .. $#list;
    my $end_pos  = $#position;
    my $done     = undef;

    return sub {
        return () if $done;
        my $cur = $end_pos;
        {
            if ( ++$position[ $cur ] > $stop[ $cur ] ) {
                $position[ --$cur ]++;
                redo if $position[ $cur ] > $stop[ $cur ];
                my $new_pos = $position[ $cur ];
                @position[ $cur .. $end_pos ] = $new_pos .. $new_pos + $by;
            }
        }
        $done = 1 if $position[0] == $stop[0];
        return @list[ @position ];
    }
}
__END__
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5

Notice that the only looping construct in the entire thing is a bare block.  It is very fast ;-)
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.