develooper Front page | perl.perl5.porters | Postings from June 2021

Re: RFC 0004 - defer {} syntax

Thread Previous | Thread Next
From:
Ben Bullock
Date:
June 17, 2021 01:45
Subject:
Re: RFC 0004 - defer {} syntax
Message ID:
CAN5Y6m-5oYYV6VsdfsS6Yb7uTK2BXyzjNzvn_NjqWSskh0jkfA@mail.gmail.com
On Thu, 17 Jun 2021 at 09:50, Tom Molesworth <tom@binary.com> wrote:

> On Thu, 17 Jun 2021 at 08:37, Ben Bullock <benkasminbullock@gmail.com>
> wrote:
>
>> I can imagine cases where you might want to clean up after each go around
>> of a loop. But I find it quite hard to imagine how it would be useful to
>> have a function which runs at the end of an "if" statement block regardless
>> of what else happens.
>>
>
> As a generic example:
>
> if($resource->acquire) {
>  defer { $resource->release; }
>  ... return, exception, next, or similar action here ...
> }.
> # This line is never reached, so the ->release doesn't happen
> # $resource->release;
>

To clarify, in terms of your example, my query is about this:

sub superduper
{
   if ($resource->acquire) {
       defer { $resource->release }
       if ($resource->failure) {
             # Case failure: Either way it runs here
             return undef;
        }
        if (0 == -1) {
             # Case exception: Either way it runs here
             die "Oh no I have failed";
         }
         if ($resource->blocks) {
              # Case next: Either way it runs here.
              next;
          }
       # Case if block finishes: At the moment it runs here <-----------
why does it run here?
   }
   # Case enclosing loop finishes: <------------- Why not run here instead?
   return 1;
}

> Do you have any examples in mind where this would be a better fit than
the scoped-to-block implementation currently described, though?

The "defer" is called within the "if" statement then runs at the end of the
if statement, I'm wondering why it can't run at the end of the loop
instead. Then we can do things like this:

while (1) {
   if ($resource->too_busy) {
        defer {
             $resource->close_some_connections;
        }
        # Don't want to clean up yet.
    }
    $resource->do_something;
    $resource->do_another_thing;
    # Clean up here with the defer statements.
}

The reason I'm saying it is because I can't see a big advantage from
running at the end of an if block, but I can see an advantage from being
able to run defers conditionally.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About