[英]How to get input from the terminal in Perl
我正在從終端接受問題並通過對話框發送回復,但我的程序只接受第一個輸入並重復。
例如,當我運行我的腳本時,輸出可能是這樣的:
[Eliza]: Hi, I'm a psychotherapist. What is your name?
user Input: hello my name is adam.
[Eliza]: hello adam, how are you?
[Eliza]: your name is adam
[Eliza]: your name is adam
[Eliza]: your name is adam
[Eliza]: your name is adam
[Eliza]: your name is adam
它無休止地重復。
我不知道我哪里做錯了。 如何讓我的程序從鍵盤讀取下一行?
sub hello {
print "[Eliza]: Hi, I'm a psychotherapist. What is your name? \n";
}
sub getPatientName {
my ($reply) = @_;
my @responses = ( "my name is", "i'm", "i am", "my name's" );
foreach my $response ( @responses ) {
if ( lc($reply) =~ /$response/ ) {
return "$'";
}
}
return lc($reply);
}
sub makeQuestion {
my ($patient) = @_;
my %reflections = (
"am" => "are",
"was" => "were",
"i" => "you",
"i'd" => "you would",
"i've" => "you have",
"i'll" => "you will",
"my" => "your",
"are" => "am",
"you've"=> "I have",
"you'll"=> "I will",
"your" => "my",
"yours" => "mine",
"you" => "me",
"me" => "you"
);
if ( $count == 0 ) {
$patientName = getPatientName($patient);
$count += 1;
print "Hello $patientName , How are you? \n";
}
my @toBes = keys %reflections;
foreach my $toBe (@toBes) {
if ($patient =~/$toBe/) {
$patient=~ s/$toBe/$reflections{$toBe}/i;
print "$patient? \n";
}
}
}
sub eliza {
hello();
my $answer = <STDIN>;
while ($answer) {
chomp $answer;
#remove . ! ;
$answer =~ s/[.!,;]/ /;
makeQuestion($answer);
}
}
eliza();
您的while
循環從不讀取輸入。 $answer
在循環之前得到STDIN
並且大概有一個字符串,它在while
條件下評估為真。 循環中的正則表達式不能改變這一點。
因此,不僅沒有分配給$answer
新輸入,而且在第一次迭代之后循環中沒有任何變化。 所以它永遠運行,根據相同的$answer
打印問題。
你需要
while (my $answer = <STDIN>) {
chomp $answer;
# ...
}
反而。
每次評估while (...)
的條件時,都會通過<STDIN>
讀取新輸入並將其分配給$answer
。 然后每個新問題都使用新的$answer
。 請注意如何在while
條件中聲明變量,使其僅存在於循環體內(以及聲明后的條件中)。 這是將其范圍限制在循環內需要的地方的好方法。
文件句柄 read <...>
在獲得EOF
(或出錯)並且循環終止時返回undef
。 請參閱perlop 中的 I/O 操作符。 終端上的用戶通常可以通過Ctrl-d
實現此目的。
使用命令行參數的典型 Perl 腳本將
請參閱下面的代碼。
#!/usr/bin/perl -w
# (1) quit unless we have the correct number of command-line arguments
$num_args = $#ARGV + 1;
if ($num_args != 2) {
print "\nUsage: name.pl first_name last_name\n";
exit;
}
# (2) we got two command-line arguments, so assume they are the
# first name and last name
$first_name=$ARGV[0];
$last_name=$ARGV[1];
print "Hello, $first_name $last_name\n";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.