Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl6: is there a phaser that runs only when you fall out of a loop?

Tags:

raku

Take this sample code:

#!/usr/bin/env perl6

use v6.c;

ROLL:
for 1..10 -> $r {
    given (1..6).roll {
        when 6 {
            say "Roll $r: you win!";
            last ROLL;
        }
        default {
            say "Roll $r: sorry...";
        }
    }
    LAST {
        say "You either won or lost - this runs either way";
    }
}

I'd like to be able to distinguish falling out of the loop from explicitly saying last. Ideally, there'd be a phaser for this, but as far as I can find, there is only LAST which runs in either case.

Is there an elegant way to do this? (Elegant, so without adding a $won variable.)

like image 608
mscha Avatar asked Mar 20 '16 17:03

mscha


2 Answers

We're dealing with Perl, so There's More Than One Way To Do It; one of them is using the topic variable $_ to keep the value so we can easily match against it repeatedly:

constant N = 5;
for flat (1..6).roll xx * Z 1..N -> $_, $n {
    print "roll $n: $_ ";

    when 6 {
        put "(won)";
        last;
    }

    default {
        put "(lost)";
    }

    LAST {
        print "result: ";
        when 6 { put "winner :)" }
        default { put "loser :(" }
    }
}
like image 170
Christoph Avatar answered Oct 15 '22 07:10

Christoph


Here's another way to do it. Elegant? I think reasonably so. I wish there were a separate phaser for this, though.

#!/usr/bin/env perl6

use v6.c;

constant MAX_ROLLS = 10;

ROLL:
for 1..MAX_ROLLS+1 -> $r {
    last ROLL if $r > MAX_ROLLS;

    given (1..6).roll {
        when 6 {
            say "Roll $r: you win!";
            last ROLL;
        }
        default {
            say "Roll $r: sorry...";
        }
    }

    LAST {
        say "You lost, better luck next time!" if $r > MAX_ROLLS;
    }
}
like image 24
mscha Avatar answered Oct 15 '22 07:10

mscha