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 ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.