I have this sub to prompt the user for a response.
I'd like to have something like this that times out, what's good way of doing that?

sub yn { my $question = shift; $question ||='Your answer? '; my $val = undef; until (defined $val){ print "$question (y/n): "; $val = <STDIN>; chomp $val; # $val = # $val eq 'y' ? 1 : ( # $val eq 'n' ? 0 : undef # ); if ($val eq 'y'){ $val = 1; } elsif ($val eq 'n'){ $val = 0; } else { $val = undef; } } return $val; }

(I guess what I'm missing is some kind of a counter, because the thing hangs waiting for stdin forever.. Maybe I could force to read stdin every 1 second, and thus I can count time.. but that would possibly yank the user's input before they concede, which is brutal. hmm.. )

I want to use this in tests, so that if there's no human being I can go on as needed. Are there some special precautions I should take when retrieving user input in my tests? I know they're picky about stdout (Test::Simple), right?

I want to optionally conduct intrusive tests (for example connecting to a database during testing ), defaulting to no.

update
This look interesting too, will test if the script was called via the command line?

# from http://pleac.sourceforge.net/pleac_perl/userinterfaces.html sub I_am_interactive { return -t STDIN && -t STDOUT; }
Is there a major CAVEAT? Like, only runs on POSIX (muahhaha)? Is this kind of check reliable?


In reply to prompt and timeout in tests by leocharre

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.