Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the Perl version of a Python iterator?
    primarykey
    data
    text
    <p>I am learning Perl at my work and enjoying it. I usually do my work in Python but boss wants Perl. </p> <p>Most of the concepts in Python and Perl match nicely: Python dictionary=Perl hash; Python tuple=Perl list; Python list=Perl array; etc. </p> <p>Question: Is there a Perl version of the Python form of an <a href="http://docs.python.org/library/stdtypes.html#iterator-types" rel="noreferrer">Iterator</a> / Generator? </p> <p>An example: A Classic Python way to generate the Fibonacci numbers is: </p> <pre><code>#!/usr/bin/python def fibonacci(mag): a, b = 0, 1 while a&lt;=10**mag: yield a a, b = b, a+b for number in fibonacci(15): print "%17d" % number </code></pre> <p>Iterators are also useful if you want to generate a subsection of a much larger list as needed. Perl 'lists' seem more static - more like a Python tuple. In Perl, can <code>foreach</code> be dynamic or is only based on a static list?</p> <p>The Python form of Iterator is a form that I have gotten used to, and I do not find it documented in Perl... Other than writing this in loops or recursively or generating a huge static list, how do I (for ex) write the Fibonacci subroutine it in Perl? Is there a Perl <code>yield</code> that I am missing? </p> <p>Specifically -- how do I write this:</p> <pre><code>#!/usr/bin/perl use warnings; use strict; # yes -- i use those! sub fibonacci { # What goes here other than returning an array or list? } foreach my $number (fibonacci(15)) { print $number . "\n"; } </code></pre> <p>Thanks in advance to being kind to the newbie...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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