How can I get Perl to enter data from STDIN one character at a time?

I'm a little new to Perl (compared to the people here). I know enough to be able to write programs for many tasks using the command line. At some point, I decided to write a command line game that built a maze and allowed me to solve it. In addition to high-quality graphics, the only thing that was missing was the ability to use WASD controls without pressing the enter button after each step that I made in the maze.

For my game to work, I want Perl to use a single character as input from STDIN, without requiring me to use something to separate the input, for example, the default \n . How would I do that?

I tried to find a simple answer on the Internet and in the book that I have, but I didn't seem to find anything. I tried setting $/="" but it seems to have bypassed all the input. I think there may be a very simple answer to my question, but I also fear that this may not be possible.

Also, does $/="" really bypass the input, or does it accept the input so quickly that it assumes there is no input if I haven't pressed a key yet?

+6
source share
3 answers

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 default input delimiter is a new line. This affects Perl's idea of ​​what a line is. Works as an awk RS variable, including treating empty lines as a terminator if it is set to a zero line (an empty line cannot contain spaces or tabs).

+4
source

If you use * nix, you will find Curses useful.

It has a getch method that does what you want.

Term :: TermKey also looks like a potential solution.

+1
source

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

 $/ = \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>; 

he will read 1 character for each assignment. From perlvar "Setting $ / to an integer reference, a scalar containing an integer, or a scalar that converts to an integer, will try to read records instead of strings, with the maximum record size being a reference integer characters."

-1
source

Source: https://habr.com/ru/post/904721/


All Articles