【问题标题】:Querying cursor position with ANSI escape codes使用 ANSI 转义码查询光标位置
【发布时间】:2013-05-03 23:41:47
【问题描述】:

如何在 perl 中使用 ANSI 转义码来查询光标位置?

我在努力

use strict;

my $variable;

open GRABSTDOUT, '>', \$variable or die "Can't open STDOUT: $!";
select GRABSTDOUT;

print "\e[6n";
select STDOUT;

print "Cursor location is >$variable<\n";
print "Bye\n";

但是查询结果没有被我的变量捕获

mymachine:~/play> perl ansi.pl
Cursor location is ><
Bye
^[[36;21Rmymachine:~/play> ;21R

【问题讨论】:

  • 是什么让您认为这可行? GRABSTDOUT 是什么?
  • GRABSTDOUT 是我将其输出重定向到我的变量的文件句柄;然后我选择 GRABSTDOUT 将 STDOUT 替换为默认输出,希望当我打印 ANSI 代码时,它会被重定向到我的变量。代码可能很粗糙,但它的目的是表明我的意图。

标签: perl


【解决方案1】:

在查看了建议的链接 (How can I get position of cursor in terminal?) 之后,我想出了下面这段可怕的代码,它可以满足我的要求,尽管还有很多改进的余地:

use strict;

my $x='';
system "stty cbreak </dev/tty >/dev/tty 2>&1";
print "\e[6n";
$x=getc STDIN;
$x.=getc STDIN;
$x.=getc STDIN;
$x.=getc STDIN;
$x.=getc STDIN;
$x.=getc STDIN;
system "stty -cbreak </dev/tty >/dev/tty 2>&1";

my($n, $m)=$x=~m/(\d+)\;(\d+)/;
print "\nCursor location is $n,$m\n";
print "Bye\n";

基本上,当您进行 ANSI 代码查询时,回复会发送到 STDIN,就好像您在终端上输入的一样,而不是我认为的 STDOUT。你可以使用

$x=<STDIN>;

但在这种情况下,用户需要按 ENTER 才能捕获回复。

使用 getc 解决了这个问题,但从我读到的内容来看它很棘手并且存在可移植性问题。 (How can I get user input without waiting for enter in Perl?http://perldoc.perl.org/functions/getc.html)。

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多