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

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

When I use the perl package Term::Screen and gets some input from user, newline's ASCII value is returning as 13. And, when I comment the use of Term::Screen, the ASCII value is returning as 10.

How does it got change?

use Term::ReadKey; # use Term::Screen; # my $scr; # $scr = Term::Screen->new; # unless ($scr) { die "Couldn't create object for Term::Screen\n"; } # $scr->clrscr; # Get the user name and password my ($user, $key); print "\nYour name: "; ReadMode 4; # Turn off controls keys while (1) { $key = ReadKey(0); if (ord($key) == 13) { print "Newline got at 13"; last; } if (ord($key) == 10) { print "Newline got at 10"; last; } print $key, "--", ord($key),"\n"; } print $key, "--", ord($key),"\n"; ReadMode 0; # Reset tty mode before exiting

Replies are listed 'Best First'.
Re: Ascii value is different
by almut (Canon) on Apr 19, 2010 at 12:56 UTC

    Term::Screen calls stty raw -echo under the hood, which unsets the tty feature "translate carriage return to newline" (icrnl) — i.e. "raw" means (among other things) -icrnl.

    Not sure if there are better ways... but a quick hack might be to patch Term::Screen to issue stty raw -echo icrnl instead, or maybe call stty icrnl yourself from your script after having used Term::Screen  (haven't tested it for side effects, though).

    Your script with Term::Screen commented (just for demo):

    $ stty -icrnl $ ./835470.pl Your name: a--97 b--98 --13ine got at 13 $ stty icrnl $ ./835470.pl Your name: a--97 b--98 Newline got at 10 --10
Re: Ascii value is different
by cdarke (Prior) on Apr 19, 2010 at 13:13 UTC
    UNIX terminals can run in canonical ('cooked') or non-canonical ('raw') mode. The difference is that in canonical mode certain characters are converted, for example Ctrl+c generates (by default) a SIGINT and <Return> gets translated to a new-line (crtonl).

    The documentation for Term::Screen clearly states that it runs in raw mode, which means there is no conversion. ASCII character 13 is a CR, the code for the return key, in canonical mode this gets translated to 10, which is LF (a line feed).


    Term::ReadKey has a ReadMode function which you could use to get consistent results.
    See also, on the shell command-line, stty -a