Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: writing to stdin

by ambs (Pilgrim)
on Mar 28, 2005 at 12:43 UTC ( [id://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?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2024-04-20 00:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found