[OT] Should exist / does exist?

Matt Lawrence matt.lawrence at virgin.net
Thu Dec 7 10:12:05 GMT 2006


Andy Armstrong wrote:
> 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
>
>
Couldn't you write methods in your iterator class called next, last, 
redo or whatever to signal the outer loop via die and eval {}?

You wouldn't get the nice natural Perl syntax, but you would have the 
freedom to implement any kind of loop control you wanted, even ones that 
Perl doesn't support.

Matt



More information about the london.pm mailing list