我有一个带有这个接口(interface)的迭代器:$hit->next_hsp
列出它的当前实现是:
my @list;
while ( my $hsp = $hit->next_hsp ) {
push( @list, $hsp );
}
现在我在想可能有更好的方法可以用更少的代码来做到这一点。你说什么,堆垛机?
最佳答案
我见过的所有迭代器都返回 undef
表示他们已经筋疲力尽。因此你应该写while (defined(my $hsp = $hit->next_hsp))
.下面的示例演示了测试真值(在 1 处中止)而不是定义性(通过“升空”)的问题中的错误。
use 5.010;
my $hit = __PACKAGE__;
sub next_hsp {
state $i;
$i++;
return ['mumble', 4, 3, 2, 1, 0, 'liftoff']->[$i];
}
# insert snippet from question here
关于perl - Perl 中将迭代器扩展为列表的最优雅的方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3901592/