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

Re: RFC 0004 - defer {} syntax

Thread Previous | Thread Next
From:
Tom Molesworth via perl5-porters
Date:
June 21, 2021 02:08
Subject:
Re: RFC 0004 - defer {} syntax
Message ID:
CAGXhHd=X3W1Hmdyz19=zhozoGNV2ZWX2MUyMgfUPXWRdyBd1FQ@mail.gmail.com
On Mon, 21 Jun 2021 at 09:36, Ben Bullock <benkasminbullock@gmail.com>
wrote:

> So I can't see what benefit there is in being able to defer to the end of
> an if block scope. Did I miss something obvious?
>
> It might be easier to understand for some people if set up this way, but
> for me it was quite confusing why the defer would need to be run at the end
> of if {}.
>

Because it happens when leaving scope - any scope, could be
if/while/try/catch/do...while 0/eval/bare block, they're all treated the
same, and this behaviour already applies for lexical scoping:

Anything introduced in the if() block - including `if(my
$variable_scoped_to_if_statement = ...)` - goes out of scope at the end of
the if() block.

Scope::Guard also triggers the guard sub when leaving the scope of the if()
block, rather than happening at some later point.

Unless you're proposing a change to that behaviour as well - something that
would cause a lot of breakage! - then having defer behave differently
introduces unnecessary consistency.

If you want something to execute in the parent scope, that can be done by
putting the defer above the if() statement. How would the following be
implemented with your suggested change in behaviour?

if(condition) {
 open my $fh, '>', 'output' or die;
 defer { $fh->close and send_email_from_file('output') }
 ... arbitrary code which may include next/return/die/goto ...
}
open my $fh, '>', 'output' or die;
...

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