Put print statements into your subs (Basic debugging checklist), and you'll see that $value will never change, since all that that sub is returning is $from+$step every time it's called. You have to move the my $value=$from; outside of that sub so that it will close over it (closures).

By the way, Want seems to mess with the internals, and it has several open bugs in regards to segfaults. The typical approach to iterators is to have them return undef at the end of the sequence, and you can also overload the <> operator, as I did in Algorithm::Odometer::Tiny (note that overloading <> in list context only works on Perl 5.18 and up). By the way, the book Higher-Order Perl is an excellent read in regards to iterators and all the things you can do with them.

use warnings; use strict; use Want 'howmany'; sub multi_iterator { my ($iterator) = @_; return sub { my $context = wantarray(); print "multi_iterator called, <$context>\n"; return unless defined $context; return $iterator->() unless $context; return map { $iterator->() } 1 .. howmany(); }; } sub counter { my ($from, $to, $step) = @_; $step ||= 1; my $value = $from; return sub { print STDERR "counter called, $from / $to / $step / $value\n"; return if $value > $to; my $v = $value; $value += $step; return $v; }; } my $counter = counter(1, 10, 3); my $iterator = multi_iterator($counter); my ($un, $deux) = $iterator->(); my $trois = $iterator->(); print "Hack-27 ", $un, ",", $deux, ",", $trois, "\n"; __END__ multi_iterator called, <1> counter called, 1 / 10 / 3 / 1 counter called, 1 / 10 / 3 / 4 multi_iterator called, <> counter called, 1 / 10 / 3 / 7 Hack-27 1,4,7

In reply to Re: iterator w/ wantarray() by haukex
in thread iterator w/ wantarray() by cmic

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.