Cody Fendant has asked for the wisdom of the Perl Monks concerning the following question:

I'm having one of those days when my brain won't work properly. How do I write a method for my module which returns a bunch of things, not all at once at the end, but one by one as a slow process happens?

Something like what happens when I fetch from a database with DBI: while($thing = getNextThing()){ ### do something } where my getNextThing() takes a while, depends on unreliable internet access, may return 1000 things etc.

If I return my sub is finished. I need to send a bunch of things back one by one, and send undef after they're all done to stop the while.

Replies are listed 'Best First'.
Re: I want to write a method that can be used with 'while ($thing = getNextThing() )'
by choroba (Cardinal) on Aug 20, 2016 at 07:20 UTC
    The name of such a thing is iterator. It's usually implemented as a closure. Now you can start searching for the two terms.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      For example, this one goes in circles

      my $coco = do { my @colors = qw[ pink maroon green OliveDrab4 PaleVioletRed3 RosyB +rown2 PeachPuff4 WhiteSmoke azure3 chartreuse1 coral3 gold1 firebrick +4 linen salmon4 tomato2 ]; my $ix = 0; my $size = int(@colors) ; sub { my $mod = $ix % $size; my $cix = $mod; warn "$ix $cix $colors[ $cix ]\n"; $ix++; return $colors[ $cix ]; }; }; $coco->() for 1 .. 100;

        Thanks! Got it working now.

Re: I want to write a method that can be used with 'while ($thing = getNextThing() )'
by kroach (Pilgrim) on Aug 20, 2016 at 10:05 UTC
    What you need is an iterator. I recommend you read the chapter on iterators in Higher Order Perl.

      Thanks! I've hacked something together but I'll read it now.