seank has asked for the wisdom of the Perl Monks concerning the following question:

I have a subroutine that I cannot modify, that asks a number of yes-no style questions and waits for STDIN before continuing. I would like to invoke this subroutine and feed it yes to all the questions. How do I do this? (To clarify on what I am trying to do see the following exemplary pseudo-code. I know some of the syntax is not proper Perl. )
sub askQuestions() { my $answer; my $isHumane; my $isStinky; print "Are you humane? "; $answer = getStringReadFromStdin(); # Will wait for input. if ($anwser eq "yes") { $isHumane = 1; } else { $isHumane = 0; # Should be ashamed of yourself } print "Do you smell? "; $answer = getStringReadFromStdin(); # Will wait for input. if ($anwser eq "yes") { $isStinky = 1; # Take a shower. } else { $isStinky = 0; } } sub askQuestionWrapper() { while (askQuestions() << print "yes") { } } askQuestionWrapper();
  • Comment on How do I automatically feed multiple yes'es into a subroutine that waits on reads from STDIN?
  • Download Code

Replies are listed 'Best First'.
Re: How do I automatically feed multiple yes'es into a subroutine that waits on reads from STDIN?
by FunkyMonk (Bishop) on Aug 28, 2007 at 16:21 UTC
    You could supply an alternative definition for getStringReadFromStdin. Eg
    { no warnings 'redefine'; local *{main::get_input} = sub { "yes" }; get_answers(); } sub get_answers { print "Is this right?"; return get_input(); } sub get_input { <> }

    The bare block at the top redefines get_input so that it returns 'yes', rather than input from STDIN. The redefinition is local to the block.

Re: How do I automatically feed multiple yes'es into a subroutine that waits on reads from STDIN?
by Anonymous Monk on Aug 28, 2007 at 16:12 UTC
    • You could redirect STDIN to a pipe from within the script.

    • You could redirect STDIN to a pipe from outside the script.

      perl wrapper.pl | perl game.pl
    • You could redirect STDIN to a buffer.

      { my $answers = "yes\nyes\n"; local *STDIN; open STDIN, '<', \$answers; # Requires Perl 5.8.0 askQuestions() }
    • You could tie STDIN.

    - ikegami