2016-01-04 41 views
2

远离Perl一会儿,并且想修改我很早以前写作艺术项目的脚本。原始脚本使用Term :: ReadKey允许用户在Mac/Linux终端中输入任意文本。当他们键入时,文本会在终端中创建各种浮动模式。 我想修改脚本,而不是在输入键时读取键,它可以从另一个进程定期写入的文本文件中读取。但是它需要以某种可控的方式(不是一次全部)读取字符,以便(粗略地)模拟人类打字。Perl术语:: ReadKey - 从文件中读取,好像它正在输入

我已经试过: 期限:: ReadKey的手册页说,它可以从一个文件句柄,而不是标准输入读 - 但由于某些原因,我不能得到这个工作,用一个标准的文件或一个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 

回答

1

这里的问题是,你的脚本可以尝试从文件中读取的“肉”所有你想要的,但如果实际写入文件的进程一次冲刷出来,你将把所有东西放在一起。

而且,几件事情:

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

  • 还要检查Term::ReadKey,你会看到,你可能要像ReadKey 0, $file

  • 它可能是最好的,如果你彻底放下期限:: ReadKey和使用File::Tail相反,在添加的字符循环一次一个

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

+0

有趣的想法,但我没有得到任何工作。 File :: Tail似乎没有帮助解决时序问题。尝试了所有的Term :: ReadKey建议,但问题不在于这些角色一次吐出来;当我从文件夹中读取字符时,根本不会吐出。尝试正常的文件以及fifo。 – artistwhocodes