基本的perl条件脚本不起作用

时间:2015-04-25 18:32:59

标签: perl

我是perl的初学者,并且一直在努力创建小脚本。我不确定这里有什么问题,但它每次都落到else,好像我输入的内容都不满足ifelsif条件。是因为eq是错误的运营商吗?或者我的代码中还有其他错误吗?谢谢!

#!/usr/bin/perl
use strict;
use warnings;
print "what is your name?\n";
my $name = readline STDIN; 
print "Hello $name How are you today?\n";

my $feeling = readline STDIN;

if ($feeling eq "happy") {
    print "that's good!\n";
}
elsif ($feeling eq "good") {
    print "okay!\n";
}
else {
    print "Interesting\n";
}

2 个答案:

答案 0 :(得分:2)

使用chomp($feeling);

#!/usr/bin/perl
use strict;
use warnings;
print "what is your name?\n";
my $name = readline STDIN;
chomp($name);
print "Hello $name How are you today?\n";

my $feeling = readline STDIN;

chomp($feeling);
if ($feeling eq "happy") {
 print "that's good!\n";
}
elsif ($feeling eq "good") {
 print "okay!\n";
}
else {
 print "Interesting\n";
}

readline STDIN会将输入的所有字符与最后输入的匹配项\n一起捕获,例如,如果您输入"happy"并按{Enter> $feeling,则接受"happy\n"通知{ {1}}是因为输入匹配以删除上一个\n换行符使用chomp删除任何尾随字符串

答案 1 :(得分:0)

chomp用于“扼杀”输入记录分隔符,默认情况下是换行符。

#!/usr/bin/perl

use strict;
use warnings;
use 5.012;                               # to use things like 'say' and 'given'

say "what is your name?";                # 'say' is like 'print', but means you don't have to use '\n'

my $name = <STDIN>;                      # good to include angled brackets <>
chomp($name);                            # remove the newline when entering the number

say qq{Hello $name, how are you today?}; # qq{} acts like double-quotes ("")

my $feeling = <STDIN>;
chomp $feeling;                          # notice parenthese aren't always needed
                                         # you could also do chomp(my $feeling=<STDIN>);

given (lc $feeling){                     # 'given' is Perl's version of a Switch and lc makes input lowercase
   when('happy') { say q{That's good.} } # q{} acts like single-quotes ('')
   when('good')  { say q{Okay!}        }
   default       { say q{Interesting}  } # your else-case
}

正如警告所示,given是实验性的,直到找到智能匹配。如果你选择的话,使用if-elsif-else结构是完全可以接受的。