Course of Raku / Advanced / Control flow / Block-related phasers / Exercises / Clean up on leave

Solution: Clean up on leave

Here is a possible solution to the task.

Code

sub work {
    LEAVE say 'Cleanup';

    say 'Working';
    return;
    say 'never reached';
}

work();

🦋 You can find the source code in the file clean-up-on-leave.raku.

Output

Working
Cleanup

Comments

  1. After Working is printed, the return exits the subroutine immediately, so never reached is never printed.

  2. Even though the body was left early, the LEAVE phaser still fires on the way out, printing Cleanup. This guarantee is exactly why LEAVE is the right place to release resources — it runs no matter how the block ends.

Course navigation

Clean up on leave   |   Enter a block