While using IO::Prompter I'm asking only numbers as input. This works. However I can't seem to find an elegant way to move away from the subroutine if I enter something like 'quit'.
In the documents it said something like:
while (my $cmd = prompt '>', -fail=>'quit') {
...
}
But I haven't been able to implement that and tried the following that doesn't function properly (I can't quit).
#!/usr/bin/perl
use strict;
use warnings;
use IO::Prompter;
my $ask = prompt "Do you want to show numbers?", -yn;
print "You entered: $ask\n";
if ( $ask eq 'y' ) {
showNumbers();
}
else {
print "You said: no\n";
}
sub showNumbers {
while ( prompt -num, 'Enter a number'){
print "$_\n";
}
}
-DEF
can be used to provide a default that's not a valid response, allowing us to distinguish between a valid a response and just pressing Enter.
sub showNumbers {
while (1) {
my $num = prompt 'Enter a number', -num, -DEF => "";
# $num is a weird value that true even for an empty string, so
# we must separately check for false (meaning EOF) and empty string.
last if !$num || $num eq "";
print "$num\n";
}
}