如果语句输出错误

时间:2015-11-09 15:07:59

标签: perl

我正在创建一个可以选择3种不同语言的小程序 输出Ruby,Python或数组中的随机元素。

然而,我的if语句显然有一个语法错误,因为无论我尝试什么,我都会得到这个:

syntax error at test.pl line 15, near ") {"
syntax error at test.pl line 17, near "} elsif"
Execution of test.pl aborted due to compilation errors.

这是我现在的代码:

sub welcome {
    my @choices = qw( Perl Python Ruby );
    my $lang = 3;
    print("Welcome, to the test script, this will test what language you would like to learn.. In order to find out these choices, write this same definition in all three different languages\n");
    print("There are",  $lang,  "languages to chose from please pick one:\n");
    print "@choices";
    my $choice = <STDIN>;
    chomp $choice
    if ($choice = "Ruby") {
        print("You have chosen Ruby!\n");
    } elsif ($choice = "Python") {
        print("You have chosen Python!\n");
    } else {
        print("You're already writing in Perl!! Let me choose for you:");
        my $rand_elm = @choices[rand @choices];
    }
}
welcome();

我也试过这个:

my $choice = <STDIN>;
chomp $choice
if ($choice = "Ruby") 
{
    print("You have chosen Ruby!\n");
} 
elsif ($choice = "Python")
 {
    print("You have chosen Python!\n");
} 
else
 {
    print("You're already writing in Perl!! Let me choose for you:");
    my $rand_elm = @choices[rand @choices];
}
}

我还尝试使用strict;warnings

我也试过了STDIN

所有这些都输出相同的错误。导致此错误的原因是什么?

2 个答案:

答案 0 :(得分:5)

您在以下情况后错过了分号:

chomp $choice

请注意以下内容是有效声明:

chomp $choice if ($choice = "Ruby")

顺便说一下,

$choice = "Ruby"

应该是

$choice eq "Ruby"

=是标量赋值或列表赋值运算符。
==是数值比较运算符。
eq是字符串比较运算符。

答案 1 :(得分:0)

您在行;

之后错过了chomp $choice

始终在脚本中加入use strict;use warnings;