4 ms·
Perl6 has a fallthrough keyword named `proceed`. It also has a keyword named `succeed` which is the default for `when` blocks. given 1 { when Int { s
by b2gills 7y ago
Perl6 has a fallthrough keyword named `proceed`. It also has a keyword named `succeed` which is the default for `when` blocks.
given 1 {
when Int { say 'integer'; proceed }
if 0 ≤ $_ ≤ 9 { say 'digit'; succeed }
when 1 { say 'one'; proceed }
}
The above will print two lines `integer` and `digit`. It will not get a chance to run the second `when` block because of the `succeed` that gets run before it.
If you want the `given` block to return a value, `succeed` can be given a value.
my $result = do given $example {
when 1 { 'one' }
when 2 { succeed 'two' } # succeed is redundant here
if $_ == 3 { succeed 'three' } # acts like a `when` block and returns "three"
…
}
---
Perl6 is “supposed” to have a `goto` keyword, but nobody has implemented it. Mainly because of a lack of need.
One of the few good uses of `goto` in a higher level language is to have a portion of a function always run at the function exit.
Perl6 has `LEAVE`, `KEEP`, and `UNDO` which handles this nicely.
sub foo (){
my $fh = open 'example.txt', :r;
LEAVE $fh.close; # close $fh at scope exit
… # use the opened file handle
}
Technically it would probably be better to have the `.close` be conditional on whether the $fh was successfully opened.
sub foo (){
my $fh = open 'example.txt', :r;
LEAVE with $fh {.close}
without $fh {.throw}; # throw the error in `$fh`
# (This isn't necessary, as it will get thrown as soon as you use it.)
… # use the opened file handle
}