Using POSIX termios
Problem
You’d like to manipulate your terminal characteristics directly.
Solution
Use the POSIX termios interface.
Description
Think of everything you can do with the stty command—you can set everything from special characters to flow control and carriage-return mapping. The standard POSIX module provides direct access to the low-level terminal interface to implement stty-like capabilities in your program.
Example 15.2 finds what your tty’s erase and
kill characters are (probably backspace and Ctrl-U). Then it sets
them back to their original values out of antiquity,
# and @, and has you type
something. It restores them when done.
Example 15-2. demo POSIX termios
#!/usr/bin/perl -w
# demo POSIX termios
use POSIX qw(:termios_h);
$term = POSIX::Termios->new;
$term->getattr(fileno(STDIN));
$erase = $term->getcc(VERASE);
$kill = $term->getcc(VKILL);
printf "Erase is character %d, %s\n", $erase, uncontrol(chr($erase));
printf "Kill is character %d, %s\n", $kill, uncontrol(chr($kill));
$term->setcc(VERASE, ord('#'));
$term->setcc(VKILL, ord('@'));
$term->setattr(1, TCSANOW);
print("erase is #, kill is @; type something: ");
$line = <STDIN>;
print "You typed: $line";
$term->setcc(VERASE, $erase);
$term->setcc(VKILL, $kill);
$term->setattr(1, TCSANOW);
sub uncontrol {
local $_ = shift;
s/([\200-\377])/sprintf("M-%c",ord($1) & 0177)/eg;
s/([\0-\37\177])/sprintf("^%c",ord($1) ^ 0100)/eg;
return $_;
}Here’s a module called HotKey that implements a
readkey function in pure ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access