2

离开 Perl 一段时间,想修改我很久以前作为艺术项目编写的脚本。原始脚本使用 Term::ReadKey 允许用户在 Mac/Linux 终端中输入任意文本。当他们键入时,文本会在终端中创建各种浮动模式。我想调整脚本,而不是在输入键时读取它们,它可以从另一个进程定期写入的文本文件中读取。但它需要以某种可控的方式(不是一次全部)读取字符,以便(大致)模仿人类打字。

我试过什么: Term::ReadKey 的手册页说它可以从文件句柄而不是 STDIN 读取 - 但由于某种原因,我无法使用标准文件或 FIFO 来实现它。我还尝试使用“打开”从文件中读取文本并将字符放入数组中。但是遍历数组变得很复杂,因为需要在字符之间添加延迟而不暂停脚本的其余部分。(我可以将其设想为一个潜在的解决方案,但我不确定如何最好地设计它以允许时间延迟是可控的,而脚本不会变得笨拙。)

想知道是否有一种相对简单的方法来解决这个问题——假设它完全可行?

这是现有脚本的“肉”(删除了各种子程序,这些子程序会根据各种按键添加额外的效果。)

#!/usr/bin/perl

use Time::HiRes(usleep);
use Term::ReadKey;


$|=1;

$starttime = time;
$startphrase = '                    ';

$startsleepval = 3000;

$phrase = $startphrase;
$sleepval = $startsleepval;
$dosleep = 1;


$SIG{'INT'}=\&quitsub;
$SIG{'QUIT'}=\&quitsub;

# One Ctrl-C clears text and resets program.  # Three Ctrl-C's to quit.

sub quitsub {print color 'reset' if ($dosleep); $phrase = $startphrase; $sleepval=$startsleepval; $SIG{'INT'}=\&secondhit;}
sub secondhit { $SIG{'INT'}=\&outtahere; }
sub outtahere {print color 'reset'; sleep 1; print "\n\n\t\t\t\n\n"; exit(0);}


while (1) {
    print "$phrase  ";
    if ($dosleep) {
        usleep ($sleepval);
    }
    ReadMode 3;

    ##### Here is where it reads from the terminal.  Can characters be read from a file in a similar sequential fashion? #####
    $key = ReadKey(-1);
    $now = time;
    if ((defined($key)) and ($now > $starttime + 5)) {
        $phrase = $phrase.$key;
        $SIG{'INT'}=\&quitsub;
    }
    # user can also create interesting effects with spacebar, tab and arrow keys.

    ReadMode 0; # this may appear redundant, but has a subtle visual effect. At least that's what I commented in the original 2003 script.

}

# end main loop
4

1 回答 1

1

这里的问题是您的脚本可以尝试从文件中读取您想要的所有内容,但是如果实际写入文件的进程一次全部刷新,您将把所有内容放在一起。

另外,有几点:

  • 如果您真的想使用 ReadKey,ReadMode 5如果您不知道文件的 CR 或 CR/LF 用途,您可能应该使用。

  • 还要检查Term::ReadKey,你会发现你可能想要类似的东西ReadKey 0, $file

  • 最好完全放弃 Term::ReadKey 并改用File::Tail,一次循环一个添加的字符

  • 就像您已经尝试过的那样,您的最终代码很可能是经过一系列字符的代码。

于 2016-01-04T08:49:05.067 回答