Here's a little subroutine I find quite handy when writing configuration scripts (or anything that needs to prompt for values from the shell). It lets you provide a prompt string and default arguments, and also lets you force the user to choose from a default list of args.

Example:

my @choices = ("yes", "no", "y", "n"); my $choice = query("Can you use an array for the choices?", "YES", @ch +oices); my $otherChoice = query("Can you use an invalid default to force them +to type in their choice?", "yes/no", "yes", "y"); my $finalChoice = query("Oh, just enter whatever you want.");

Hope you find this useful. ;)

Edit: Changed to a while(1) loop, and checked $_[0] on advice of q[uri] in efnet #perl
Edit2: Ditched array and used named scalars instead for clarity, also took a couple clues from Jeffa++ (grep/chomp directly). Now you can supply a null default and it will work. ;) Unless you supply a list of choices of course.
# &query(Prompt String, optional default, optional list of restrictive + choices) # If the choices are provided at the end, only one of those can be ch +osen. # This is currently case insensitive. # # Example: my $val = query("Do you like config scripts?", "yes", "yes" +, "no", "y", "n"); # Will print: Do you like config scripts? [yes]: # The user can either press enter for yes, or enter one of the other a +rguments. sub query { my $prompt = (defined $_[0]) ? $_[0] : ""; my $default = (defined $_[1]) ? $_[1] : ""; my $answer; while(1) { print "$prompt [$default]: "; chomp($answer = <STDIN>); $answer = $default if ($answer eq ""); last unless $#_ > 1; last if grep $answer =~ /^\Q$_\E$/i, @_[2 .. $#_]; } return $answer; }

In reply to Prompting via shell with default arguments by Azhrarn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.