Skip to content

[EXPERIMENT] defer {} syntax #17949

Open
Open
@leonerd

Description

@leonerd

(copied from https://www.nntp.perl.org/group/perl.perl5.porters/2020/06/msg257611.html )

I'm trying to simplify the design of a try/catch syntax out of Syntax::Keyword::Try so it can be moved into core perl. One thing I think we can get rid of is the finally keyword, in favour of instead inventing a new LEAVE phaser block, similar to the Raku ones.

In summary: I'd like to add LEAVE with syntax which looks like another phaser such as END, but runs at the time you leave the block it is placed in:

  sub f {
    print 1;
    LEAVE { print 3; }

    print 2;
  }

  f();

Will output

123

Furthermore, a LEAVE phaser inside something like a foreach loop would run every time you leave the block in order to run a new one:

  foreach (qw( a b c )) {
    print "Start($_)";
    LEAVE { print "End($_)"; }

    more code here...
  }

will output

Start(a)End(a)Start(b)End(b)Start(c)End(c)

Seems simple enough.

It is important to note that a LEAVE block is similar to an END block, in that the mere presence of that syntax is enough to queue it for being run, regardless of whether the line of code it's on was actually "reached". Thus, just as in

  exit 0;
  END { say "Ending the program now" }

still prints, so too would

  sub f {
    return;
    LEAVE { say "Leaving the function now" }
  }

If we had a LEAVE phaser (totally independent of any thoughts of try/catch), it reduces the scope of that work considerably and makes it easier to work out how to implement.

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions