Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

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
getc> 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.


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2020-02-18 19:49 GMT
Find Nodes?
    Voting Booth?
    What numbers are you going to focus on primarily in 2020?

    Results (79 votes). Check out past polls.