【发布时间】:2011-04-16 01:56:54
【问题描述】:
我在工作中学习 Perl,并乐在其中。我通常用 Python 做我的工作,但老板想要 Perl。
Python 和 Perl 中的大多数概念都很好地匹配:Python dictionary=Perl hash; Python 元组=Perl 列表; Python 列表=Perl 数组;等等。
问题:有没有Iterator/Generator 的 Python 形式的 Perl 版本?
一个例子:生成斐波那契数的经典 Python 方法是:
#!/usr/bin/python
def fibonacci(mag):
a, b = 0, 1
while a<=10**mag:
yield a
a, b = b, a+b
for number in fibonacci(15):
print "%17d" % number
如果您想根据需要生成更大列表的子部分,迭代器也很有用。 Perl 的“列表”看起来更静态——更像是一个 Python 元组。在 Perl 中,foreach 可以是动态的还是仅基于静态列表?
Iterator 的 Python 形式是我已经习惯的一种形式,我没有发现它在 Perl 中记录... ex) 在 Perl 中编写斐波那契子程序?是否有我缺少的 Perl yield?
具体来说——我该怎么写:
#!/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"; }
在此先感谢您对新手的善意...
【问题讨论】: