2012-05-31 3 views
0

Я пытаюсь напечатать символ из файла каждый раз, когда я получаю 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);   
    } 
} 

ответ

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') } 
+0

сделал это, и он ничего не печатает – Tatiana

+0

Работает для меня. Я добавляю полностью улучшенную программу. – daxim

+0

+1 - в том числе для демонстрации хорошего стиля – DVK

1

Ваш исходный код имеет 3 задачи:

  • Вы только читали символ один раз (за пределами цикла for)

  • Читает 1 строку из входного файла при тестировании while (<IN>) { (LOSING, что линия!), А затем еще один в $line = <IN>; - поэтому в вашей логике только чтение строк #d

  • print "$i" печатает 1 линию, без новой строки, поэтому вы не видите символы разделены

-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 
} 
Смежные вопросы