Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is a similar method to produce a Iterator / Generator, but it is not a "first class citizen" as it is on Python.</p> <p>In Perl, if you do not see what you want (after a <strong>MANDATORY</strong> trip to <a href="http://search.cpan.org/search?query=iterator&amp;mode=all" rel="noreferrer">CPAN</a> <strong>FIRST</strong>!), you can roll your own that is similar to a Python iterator based on Perl closures and an anonymous subroutine. </p> <p>Consider:</p> <pre><code>use strict; use warnings; sub fibo { my ($an, $bn)=(1,0); my $mag=(shift || 1); my $limit=10**$mag; my $i=0; return sub { ($an, $bn)=($bn, $an+$bn); return undef if ($an &gt;=$limit || wantarray ); return $an; } } my $num; my $iter=fibo(15); while (defined($num=$iter-&gt;()) ) { printf "%17d\n", $num; } </code></pre> <p>The sub <code>fibo</code> maintains a Perl <a href="http://perldoc.perl.org/perlfaq7.html#What&#39;s-a-closure%3f" rel="noreferrer">closure</a> that allows persistent variables to be maintained. You can do the same by having a module, similar to C / C++. Inside <code>fibo</code> an anonymous subroutine does the work of returning the next data item. </p> <p>To quote from the <a href="http://rads.stackoverflow.com/amzn/click/0596000278" rel="noreferrer">Perl Bible</a> "You will be miserable until you learn the difference between scalar and list context" -- p 69 (A highly recommended book btw...)</p> <p>In this case, the annon sub only returns a single value. The only looping mechanism that I know of in Perl that can work in scalar context is <code>while</code>; The others try to fill the list before proceeding I think. Therefor, if you called the anon sub in list context, it will dutifully return the next fibonacci number, unlike Python's for iterators, and the loop would terminate. That is why I put the <code>return undef if .... wantarray</code> because it does not work in list context as written. </p> <p>There are ways to fix that. Indeed, you can write subroutines that act like <code>map</code> <code>foreach</code> etc but it is not as straightforward as Python's yield. You will need an additional function to use inside a foreach loop. The tradeoff is the Perl approach has tremendous power and flexibility. </p> <p>You can read more about Perl iterators in Mark Jason Dominus' excellent book "Higher Order Perl" <a href="http://hop.perl.plover.com/book/pdf/04Iterators.pdf" rel="noreferrer">Chapter 4 is all about Interators</a> brian d foy also has an excellent <a href="http://www.theperlreview.com/Articles/v0i5/iterators.pdf" rel="noreferrer">article</a> on Interators in the Perl Review.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload