This (hopefully) has the same functionality as your code, with the execption of allowing the user of submitting nothing when there are no default arguments supplied by the programmer. (gotta love Carter's Compass! ok, ok, i just moved the return out of the loop)
sub query { my ($str,@argv) = @_; my $answer; while (1) { print "$str ", $argv[0] ? "[$argv[0]]: " : ": "; chomp($answer = <STDIN>); last unless @argv; last if grep $answer =~ /^\Q$_\E$/i, @argv; } return $answer; }
I feel inclined to replace the regular expression used in that grep to
last if grep $answer eq $_, @argv;
... i see no need to use a regex if you have to match the entire string.

UPDATE:
Ahhh, i missed that you were allowing case insensitive answers via the regex. Here is another version that uses lc to match upper and lower cases. This code also fullfills the requirement of allowing the user to pick a default option. I missed that one the first time around ;)

sub query2 { my ($str,@argv) = @_; my $answer; while (1) { print "$str ", $argv[0] ? "[$argv[0]]: " : ": "; chomp($answer = <STDIN>); return $answer if !@argv or grep lc($answer) eq lc($_), @argv; return $argv[0] unless $answer; } }
I also noticed you changed your original code. It looks much better now, but you should replace
$answer = $default if ($answer eq ""); # with this instead $answer ||= $default;

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

In reply to (jeffa) Re: Prompting via shell with default arguments by jeffa
in thread 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.