[OT] Should exist / does exist?

Andy Armstrong andy at hexten.net
Wed Dec 6 21:56:09 GMT 2006


On 6 Dec 2006, at 21:36, Paul Johnson wrote:
> #!/usr/bin/perl
>
> use strict;
> use warnings;
> no warnings "exiting";
>
> sub X::withQuery
> {
>     my $self = shift;
>     my ($loop, $sub) = @_;
>     eval <<EOE;
>     $loop:
>     for my \$l (1 .. 3)  # or whatever your loop looks like
>     {
>         \$sub->(\$l);
>     }
> EOE
>     die "argh: $@" if $@;
> }
>
> my $db = bless {}, "X";
>
> $db->withQuery(ROW => sub {
>     my $row = shift;
>     print "-- $row\n";
>     if ($row > 1) {
>         last ROW;
>     }
> });

Aha. I'm a dumbass - I didn't realise that the last|redo|next would  
percolate up to the loop within the iterator.

That pretty much satisfies what I originally asked but doesn't help  
in the case where the iterator isn't implemented as a single loop.  
I'd really like to have the kind of loop exit communicated back to  
the iterator so it can handle it in whatever way is appropriate. For  
example the iterator might actually be recursively walking some data  
structure without even containing an explicit loop

sub iter {
     my $node = shift;
     my $sub  = shift;

     iter($node->{left}, $sub) if exists $node->{left};
     $sub->($node);
     # Should redo $sub call if redo thrown
     #        carry on       if next thrown
     #        throw 'last' up the call stack
     #                       if last thrown
     iter($node->{right}, $sub) if exists $node->{right};
}

-- 
Andy Armstrong, hexten.net



More information about the london.pm mailing list