如何让Perl一次从STDIN接受一个字符? [英] How can I have Perl take input from STDIN one character at a time?

查看:119
本文介绍了如何让Perl一次从STDIN接受一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点像Perl的初学者(与这里的人相比).我了解足够多,能够通过命令提示符编写程序来执行许多操作.有一次,我决定编写一个命令迷宫游戏,该游戏构造了一个迷宫并让我解决了这个迷宫.除了高质量的图形外,唯一缺少的是我在迷宫中进行的每一个动作之后都可以使用WASD控件而无需按Enter的功能.

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 decided to write a command prompt game that constructed a maze and let me solve it. Besides quality graphics, the only thing that it was missing was the ability for me to use the WASD controls without pressing enter after every move I made in the maze.

要使我的游戏正常工作,我希望Perl可以将单个字符用作来自STDIN的输入,而无需我使用某些东西来分隔我的输入,例如默认的\n.我将如何完成?

To make my game work, I want to be able to have Perl take a single character as input from STDIN, without requiring me to use something to separate my input, like the default \n. How would I accomplish this?

我尝试在网上和一本书中寻找一个简单的答案,但似乎没有找到任何答案.我尝试设置$/="",但这似乎绕过了所有输入.我认为对我的问题可能有一个非常简单的答案,但我也担心这可能是不可能的.

I have tried searching for a simple answer online and in a book that I have, but I didn't seem to find anything. I tried setting $/="", but that seemed to bypass all input. I think that there may be a really simple answer to my question, but I am also afraid that it might be impossible.

还有,$/=""是实际上绕过输入了吗,还是接收速度如此之快以至于假设我还没有按下该键,就可以认为没有任何输入?

Also, does $/="" actually bypass input, or does it take input so quickly that it assumes there isn't any input if I'm not already pressing the key?

推荐答案

IO::Prompt 可以使用:

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";

来自 perldoc -v '$/' 的相关摘录与设置$/ = ''有关:

输入记录分隔符,默认为换行符.这会影响Perl的 什么是线"的想法.像awk的RS变量一样工作,包括 如果将空行设置为空字符串,则将其作为终止符(空行不能包含任何空格或制表符).

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).

这篇关于如何让Perl一次从STDIN接受一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆