http://www.perlmonks.org?node_id=442788


in reply to writing to stdin

Well.. try something like:
print "Are you sure? [y]"; chomp(my $ans = <STDIN>); $ans ||= "y"; if ($ans =~ m!^y(es)?!) { # do something } else { # do otherthing }

Update: added missing chomp thanks to cog. Added some more code as asked by virtualsue.

Alberto Simões

Replies are listed 'Best First'.
Re^2: writing to stdin
by cog (Parson) on Mar 28, 2005 at 14:31 UTC
    There are two problems with the code...

    First, it's not case-insensitive...

    Secondly, an answer such as "y should I?" will match :-)

    This will do the trick:

    print "Are you sure? [y]"; chomp(my $ans = <STDIN>); $ans ||= "y"; if ($ans =~ m!^y(es)?$!i) { # do something } else { # do otherthing }

    And another approach:

    #!/usr/bin/perl print "Are you sure? [y]"; if (<> =~ /^(y(es)?)?\n$/i) { # answer was yes } else { # answer was no }
Re^2: writing to stdin
by cog (Parson) on Mar 28, 2005 at 13:18 UTC
    Actually, there's a chomp $ans; missing (otherwise, one could write my $ans = <STDIN> || 'y';, which would be quite cool...)
Re^2: writing to stdin
by virtualsue (Vicar) on Mar 28, 2005 at 13:25 UTC
    Other than the chomp problem, this code will interpret the answer "yes" as no. Maybe this is trivial, but I think it's nice to make the extra effort to do what the user really wants. :-)