Often when I write a loop I want to run some code at loop entry time. It
would be nice to have a closure trait for this, similar to NEXT for loop
continuation or LAST for loop termination, but there isn't one. I don't
think either FIRST or ENTER do quite what I want. FIRST runs only once,
which is too few times, and ENTER runs every time the loop block is entered,
which is too many.
To demonstrate what I want, consider the following examples:
sub use_first()
{
for 1..2 {
FIRST {say 'entering loop';}
say $_;
LAST {say 'leaving loop';}
}
}
sub use_enter()
{
for 1..2 {
ENTER {say 'entering loop';}
say $_;
LAST {say 'leaving loop';}
}
}
The first time use_first is called it will print
entering loop
1
2
leaving loop
but subsequently it will print
1
2
leaving loop
and leave out the 'entering loop'.
When use_enter is called it will print
entering loop
1
entering loop
2
leaving loop
I want to output
entering loop
1
2
leaving loop
every time I run my loop. I suggest we create a new closure trait called
SETUP for this. Then the code could read
for 1..2 {
SETUP {say 'entering loop';}
say $_;
LAST {say 'leaving loop';}
}
Since SETUP can be used for initialization, it should probably be allowed
within an expression:
state $first_iteration = SETUP {true} will next {$_ = false};
Lower case 'setup' could probably also be used as a trait on a variable
state $first_iteration will setup {$_ = true} will next {$_ =
false};
Joe Gottman