Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

getc vs readline

by Anonymous Monk
on Nov 30, 2019 at 15:14 UTC ( #11109483=perlquestion: print w/replies, xml ) Need Help??

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

I'm trying to use both getc (for single chars) and readline (for more than one char) to capture user input in a script. I usually just use <STDIN> but want to expand my horizons, plus getc avoids a chomp. But using getc prevents subsequent calls to readline from waiting for input! Why does it do that? For example:
print 'readline> '; $_ = readline; print $_; print 'getc> '; $_ = getc; print "$_\n"; print 'readline> '; $_ = readline; print 'WTF';
The result:
readline> x
x
getc> x
x
readline> WTF

Replies are listed 'Best First'.
Re: getc vs readline
by dave_the_m (Monsignor) on Nov 30, 2019 at 19:57 UTC
    getc() uses the same input buffer as readline. getc() won't normally return after a single character like 'X' is entered; it waits until a whole line has been entered (including \n), then returns the first character of it. readline() sees the remainder of the line still in the buffer and returns immediately. For example, if the user types "abc\n", then at the point the user presses carriage-return, getc() returns "a" and readline() immediately follows on returning "bc\n".

    If you truly want to get the next character even if the user hasn't pressed return yet, then look into something like Term::ReadKey.

    Dave.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11109483]
Approved by GrandFather
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2019-12-05 22:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (154 votes). Check out past polls.

    Notices?