Eugene Barsky
Eugene Barsky

Reputation: 6012

How to make a Perl 6 script exit on Ctrl+D input?

loop {
  my $word = prompt '> ' ;
  say $word;
}

What's the right way to make it exit if/when instead of printing a word I press Ctrl+D?

Upvotes: 4

Views: 187

Answers (2)

Elizabeth Mattijsen
Elizabeth Mattijsen

Reputation: 26969

With a little helper sub:

sub not-done(\value) {
    value but True if value.defined
}

Then you can just write your loop as:

while not-done prompt("> ") -> $word {
    say $word
}

Upvotes: 5

Keith Thompson
Keith Thompson

Reputation: 263507

I'm less familiar with Perl 6 than with Perl 5, but the Perl 5 method seems to work:

loop {
  my $word = prompt '> ' ; 
  last if not defined $word;
  say $word;
}

This might be more idiomatic:

while (defined my $word = prompt '> ') {
    say $word;
}

(Without the defined operator, the loop will terminate on an empty input.)

Upvotes: 8

Related Questions