Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: writing to stdin

by ambs (Pilgrim)
on Mar 28, 2005 at 12:43 UTC ( #442788=note: print w/replies, xml ) Need Help??


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. :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://442788]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (1)
As of 2021-10-26 23:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (91 votes). Check out past polls.

    Notices?