in reply to iter

It seems to me that your solution has two problems.

First, you cannot have more than one active iterator in your program at once.

Second, you used a lot of code!

You might prefer this object-oriented approach. The interface is almost the same as yours, but the code is only six lines long:

sub iterstart { my @a = @_; return sub { my $n = shift; $n = 1 unless defined $n; return splice @a, 0, $n; }; } @data = qw(1 fee 2 fee fi 3 fee fi fo 4 fee fi fo fum 1 fin); my $iter = iterstart @data; while (my ($len) = $iter->()) { push @lol, [$iter->($len)]; } use Data::Dumper; print Dumper \@lol;

Replies are listed 'Best First'.
Re: Re: iter
by MeowChow (Vicar) on Mar 27, 2001 at 22:25 UTC
    Actually you can have more than one active iterator; however in that case, you should explicitly specify the iterating list when calling iter. I avoided the splice-based solution because I didn't want to add the overhead of copying the array. In truth, I'm not sure how much performance this buys me, considering all the splice-ish code which is now duplicated in perl. I also prefered not to take the OO aproach because I wanted a function that would feel more like a built-in (like each, for example).

    That said, my solution is pretty ugly in comparison :)

    update: After running some benchmarks, it's apparent that my solution is less efficient (by a factor of about 7x when iterating on each individual item), since the built-in splice is considerably faster than a re-implementation of a non-destructive splice in Perl. (though, my iter does outperform the OO iter when iterating and returning segments of length 100 or greater {really big grin})

    So without further ado, -- this quote-unquote craft, and forget I ever wrote this piece of schnapz.

    update2: Oh yeah, I forgot to mention, you wrote alot of code! :p

    sub iter { my @a = @_; sub { splice @a, 0, shift || 1 }; }
      Says meowchow:
      sub { splice @a, 0, shift || 1 };
      If you do that, then $iter->(0) doesn't work properly.
        One could probably do without that "functionality"...

        ... I know, I know, boundary conditions and all that good stuff.

        Blech, I just can't win, can I? :-)