无法调用第二个子程序"func2"

use*_*481 -1 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";
}
Run Code Online (Sandbox Code Playgroud)

输出(输入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
Run Code Online (Sandbox Code Playgroud)

输出(输入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
Run Code Online (Sandbox Code Playgroud)

Bor*_*din 5

没有@fruits阵列,所以$fruit = $fruits[<STDIN>]毫无意义.$fruit将被设置undef为在数值上下文中计算为零

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

==运算符比较数字,所以if ($fruit == $fruit_list{'1'})会比较零点零始终找不到匹配

运行程序时,您必须看到警告消息.你绝不能忽视这些消息,因为它们可以帮助你

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

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