commit 50f048b798478ba98c6e8043b7e518815f9f8c3a
parent 3bac6ec762c3e48ab3d5d7fb058005ad03879646
Author: Andreas Guldstrand <andreas.guldstrand@gmail.com>
Date: Tue, 6 Sep 2016 00:06:14 +0200
SBO::Lib::Util: add prompt() routine to handle prompting the user for input
Diffstat:
1 file changed, 32 insertions(+), 0 deletions(-)
diff --git a/SBO-Lib/lib/SBO/Lib/Util.pm b/SBO-Lib/lib/SBO/Lib/Util.pm
@@ -46,6 +46,7 @@ our @EXPORT_OK = (
open_fh
open_read
print_failures
+ prompt
script_error
show_version
slurp
@@ -341,6 +342,37 @@ sub print_failures {
}
}
+=head2 prompt
+
+ exit unless prompt "Should we continue?", default => "yes";
+
+C<prompt()> prompts the user for an answer, optinally specifying a default of
+C<yes> or C<no>. If the default has been specified it returns a true value in
+case 'yes' was selected, and a false value if 'no' was selected. Otherwise it
+returns whatever the user answered.
+
+=cut
+
+sub prompt {
+ my ($q, %opts) = @_;
+ my $def = $opts{default};
+ $q = sprintf '%s [%s] ', $q, $def eq 'yes' ? 'y' : 'n' if defined $def;
+
+ print $q;
+
+ my $res = readline STDIN;
+
+ if (defined $def) {
+ return 1 if $res =~ /^y/i;
+ return 0 if $res =~ /^n/i;
+ return $def eq 'yes' if $res =~ /^\n/;
+
+ # if none of the above matched, we ask again
+ goto &prompt;
+ }
+ return $res;
+}
+
=head2 read_config
read_config();