我注意到如果我if-else用一个三元运算符替换我正在使用的语句,当我尝试运行我的代码时,我得到一个编译错误.我相信罪魁祸首就是foreach()我内心的循环if-else.你知道为什么三元运算符的行为与此实例中的if-else构造的行为不同吗?
我的代码看起来像这样
#!/program/perl_v5.6.1/bin/perl5.6.1
use strict;
use warnings;
my $fruits_array_ref = &get_fruits();
if($fruits_array_ref != 0) {
print("$_ is a fruit.\n") foreach(@$fruits_array_ref);
}
else {
print("Maybe you like vegetables?\n");
}
sub get_fruits() {
my @fruit_list;
my $shopping_list = "/home/lr625/grocery_items";
open(my $shopping_list_h, "<", $shopping_list) or die("Couldn't open.\n");
while(my $line = <$shopping_list_h>) {
next if $line =~ /^\#/;
chomp($line);
push(@fruit_list, $line);
}
close($shopping_list_h) or die("Couldn't close.\n");
scalar(@fruit_list) > 0 ? return(\@fruit_list) : return(0);
}
Run Code Online (Sandbox Code Playgroud)
我在购物清单中的数据看起来像
# this is …Run Code Online (Sandbox Code Playgroud)