Search code examples
perlinput

Perl do input one char from stdin


How can Perl do input from stdin, one char like

readline -N1

does?


Solution

  • You can do that with the base perl distribution, no need to install extra packages:

    use strict;
    sub IO::Handle::icanon {
            my ($fh, $on) = @_;
            use POSIX;
            my $ts = new POSIX::Termios;
            $ts->getattr(fileno $fh) or die "tcgetattr: $!";
            my $f = $ts->getlflag;
            $ts->setlflag($on ? $f | ICANON : $f & ~ICANON);
            $ts->setattr(fileno $fh) or die "tcsetattr: $!";
    }
    
    # usage example
    # a key like `Left` or `á` may generate multiple bytes
    STDIN->icanon(0);
    sysread STDIN, my $c, 256;
    STDIN->icanon(1);
    # the read key is in $c
    

    Reading just one byte may not be a good idea because it will just leave garbage to be read later when pressing a key like Left or F1. But you can replace the 256 with 1 if you want just that, no matter what.