How can I have Perl take input from STDIN one character at a time?

前端 未结 3 2039
走了就别回头了
走了就别回头了 2021-01-05 15:12

I am somewhat a beginner at Perl (compared to people here). I know enough to be able to write programs to do many things with through the command prompt. At one point, I dec

相关标签:
3条回答
  • IO::Prompt can be used:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use IO::Prompt;
    
    my $key = prompt '', -1;
    print "\nPressed key: $key\n";
    

    Relevant excerpt from perldoc -v '$/' related to setting $/ = '':

    The input record separator, newline by default. This influences Perl's idea of what a "line" is. Works like awk's RS variable, including treating empty lines as a terminator if set to the null string (an empty line cannot contain any spaces or tabs).

    0 讨论(0)
  • 2021-01-05 15:32

    If you are using *nix, you will find Curses useful.

    It has a getch method that does what you want.

    Term::TermKey also looks like a potential solution.

    0 讨论(0)
  • 2021-01-05 15:49

    The shortest way to achieve your goal is to use this special construct:

    $/ = \1;
    

    This tells perl to read one character at a time. The next time you read from any stream (not just STDIN)

    my $char = <STREAM>;
    

    it will read 1 character per assignment. From perlvar "Setting $/ to a reference to an integer, scalar containing an integer, or scalar that's convertible to an integer will attempt to read records instead of lines, with the maximum record size being the referenced integer number of characters."

    0 讨论(0)
提交回复
热议问题