http://qs321.pair.com?node_id=543785

I don't know if this is a common idiom, but I thought it was interesting, so I'm sharing with you.

This is a common way to return lists or references, depending on the calling context:

sub foo { # ... return wantarray? @foo : \@foo; }

Now, since I was studying how to create iterators using closures, I tried this:

sub foo { # ... return wantarray? @foo : sub { shift @foo if @foo }; }

In other words, "return a list or an iterator": we can call the function like this:

my @array = foo( $x ); foreach ( @array ) { # do something }

And we can call it "iteractivelly":

my $iter = foo( $x ); while ( my $row = $iter->() ) { # do something }

As I said, I'm not sure if this is a common idiom (or even an useful one), but it seemed interesting so I decided to share with you. : )