无法调用第二个子程序“func2”

时间:2018-05-08 08:33:41

标签: perl subroutine

编码

print "fruit list\n";
print "1.\tApple\n";
print "2.\tOrange\n";
print "3.\tPic\n";
print "3.\tBanana\n";
print "Based on fruit list above, please key in your favorite fruit name.\n";

%fruit_list = (
    1 => 'Apple',
    2 => 'Orange',
    3 => 'Pic',
    4 => 'Banana'
);

$fruit = $fruits[<STDIN>];

if ( $fruit == $fruit_list{'1'} ) {
    func1();
}
elsif ( $fruit == $fruit_list{'2'} ) {
    func2();
}

sub func1 {
    print "executing function 1\n";
}

sub func2 {
    print "executing function 2\n";
}

输出(输入1):

fruit list
1.      Apple
2.      Orange
3.      Pic
4.      Banana
Based on fruit list above, please key in your favorite fruit name.
1
executing function 1

输出(输入2):

fruit list
1.      Apple
2.      Orange
3.      Pic
4.      Banana
Based on fruit list above, please key in your favorite fruit name.
2
executing function 1

3 个答案:

答案 0 :(得分:5)

没有@fruits数组,因此$fruit = $fruits[<STDIN>]毫无意义。 $fruit将设置为undef,在数值上下文中评估为零

同时,$fruit_list{'1'}Apple,在数值上下文中也计算为零

==运算符会比较数字,因此if ($fruit == $fruit_list{'1'})会将零与零进行比较并始终找到匹配

运行程序时,您必须看到警告消息。您必须从不忽略此类消息,因为它们可以帮助您

必须use strictuse warnings 'all'添加到您编写的每个Perl程序的顶部,并在向其他人寻求帮助之前修复所有生成的消息

您还必须正确放置代码,包括缩进,以便其他人(和您自己)可以轻松阅读。我已经在你的问题中编辑了代码:请在将来自己做,至少在向其他人寻求代码帮助之前

答案 1 :(得分:1)

好像您正在使用==运算符来比较字符串:if ($fruit == $fruit_list{'1'}){和此处:elsif ($fruit == $fruit_list{'2'}){

在Perl中,==是一个数值比较运算符,用于比较字符串使用eq运算符(即if ($fruit eq $fruit_list{'1'}){)。

答案 2 :(得分:0)

感谢比较字符串和数组声明的输入。我接受了输入修改我的代码,如下所示,它按预期工作。

print "fruit list\n";
print "1.\tApple\n";
print "2.\tOrange\n";
print "3.\tPic\n";
print "3.\tBanana\n";
print "Based on fruit list above, please key in your favorite fruit name.\n";
my %fruit_list = (
    1 => 'Apple',
    2 => 'Orange',
    3 => 'Pic',
    4 => 'Banana'
    );
@values = values(%fruit_list);
my $fruit = $values [<STDIN>];
if ($fruit eq $values[1]){
func1();
}
elsif ($fruit eq $values[2]){
func2();
}

sub func1 {
print "executing function 1\n";
}

sub func2 {
print "executing function 2\n";
}

输出(输入2)

fruit list
1.      Apple
2.      Orange
3.      Pic
4.      Banana
Based on fruit list above, please key in your favorite fruit name.
2
executing function 2