为什么不能用我的字符串输入工作?

问题描述:

刚开始学习Perl,即学习程序流程 - 评估字符串和数字以及使用适当的运算符之间的主要区别。简单的脚本,我在这里让我疯狂,因为它是一个超级简单的,如果其他语句应该在“麦克风”输入时运行并且不起作用。它会输出else语句。请帮助为什么不能用我的字符串输入工作?

#!C:\strawberry\perl\bin\perl.exe 

use strict; 
#use warnings; 
#use diagnostics; 

print("What is your name please?"); 
$userName = <STDIN>; 


if($userName eq "mike"){ 
    print("correct answer"); 
} 
else{ 
    print("Wrong answer"); 
} 
+3

您是否尝试过调试您的程序?什么是$ userName的价值? – BlackBear 2011-02-03 20:27:11

+0

$ userName值将是用户输入的任何内容,作为使用的标量变量。 – 2011-02-03 20:29:59

+1

没错。但它包含用户也输入的换行符。您的比较没有考虑到这一点。 – 2011-02-03 20:32:04

当我读到你的问题时,我以为你将在字符串和数值中出现问题。考虑以下情况:

#!/usr/bin/env perl 

use strict; 
use warnings; 

print("What is the meaning of life, the universe and everything? "); 
chomp(my $response = <STDIN>); 

if ($response == 42) { 
#if (42 ~~ $response) { 
    print "correct answer\n"; 
} else { 
    print "Wrong answer\n" ; 
} 

尝试使用两种不同的if语句。回答好像family的东西,看看会发生什么。 ~~是智能匹配运算符,它在Perl中帮助解决了这个问题。详细了解它here(在“智能匹配详细”下)。还要注意chomp运算符的内联使用。

尝试增加呼叫时,从标准输入得到你的价值后的Chomp:

$userName = <STDIN>; 
chomp($userName); 

因为从STDIN读入的值将会对最终换行符。内置的chomp()将从字符串的末尾删除换行符。