每次我输入char作为输入时,我都试图从文件中打印一个字符。 我的问题是它打印整行。我知道这是一个逻辑问题,我无法弄清楚如何修复它。
use Term::ReadKey;
$inputFile = "input.txt";
open IN, $inputFile or die "I can't open the file :$ \n";
ReadMode("cbreak");
while (<IN>) {
$line = <IN>;
$char = ReadKey();
foreach $i (split //, $line) {
print "$i" if ($char == 0);
}
}
答案 0 :(得分:3)
将ReadKey
调用移至foreach
循环。
use strictures;
use autodie qw(:all);
use Term::ReadKey qw(ReadKey ReadMode);
my $inputFile = 'input.txt';
open my $in, '<', $inputFile;
ReadMode('cbreak');
while (my $line = <$in>) {
foreach my $i (split //, $line) {
my $char = ReadKey;
print $i;
}
}
END { ReadMode('restore') }
答案 1 :(得分:1)
您的原始代码有3个问题:
你只读过一次(在for
循环之外)
在测试while (<IN>) {
(丢失该行!)时读取输入文件中的1行,然后在$line = <IN>;
中读取另一行 - 因此,只读取逻辑中的#d行
print "$i"
打印1行,没有换行符,因此,您看不到分隔的字符
答案 2 :(得分:-1)
我的脚本读取目录中的所有文件,然后放入列表中,从给定列表中选择一个随机文件。 之后,每次从用户获取输入字符时,它都会从文件中输出一个字符。
#!C:\perl\perl\bin\perl
use Term::ReadKey qw(ReadKey ReadMode);
use autodie qw(:all);
use IO::Handle qw();
use Fatal qw( open );
STDOUT->autoflush(1);
my $directory = "codes"; #directory's name
opendir (DIR, $directory) or die "I can't open the directory $directory :$ \n"; #open the dir
my @allFiles; #array of all the files
while (my $file = readdir(DIR)) { #read each file from the directory
next if ($file =~ m/^\./); #exclude it if it starts with '.'
push(@allFiles, $file); #add file to the array
}
closedir(DIR); #close the input directory
my $filesNr = scalar(grep {defined $_} @allFiles); #get the size of the files array
my $randomNr = int(rand($filesNr)); #generate a random number in the given range (size of array)
$file = @allFiles[$randomNr]; #get the file at given index
open IN, $file or die "I can't open the file :$ \n"; #read the given file
ReadMode('cbreak'); #don't print the user's input
while (my $line = <IN>) { #read each line from file
foreach my $i (split //, $line) { #split the line in characters (including \n & \t)
print "$i" if ReadKey(); #if keys are pressed, print the inexed char
}
}
END {
ReadMode('restore') #deactivate 'cbreak' read mode
}