我尝试了这段代码,但它没有生效。输出结果为空。我犯了什么错误?
my %fruit_color = ("apple", "red", "banana", "yellow");
my @fruits = keys %fruit_colors;
my @colors = values %fruit_colors;
print @fruits;
print @colors;
Codepad链接: http://codepad.org/vDVAxJcp
我尝试了这段代码,但它没有生效。输出结果为空。我犯了什么错误?
my %fruit_color = ("apple", "red", "banana", "yellow");
my @fruits = keys %fruit_colors;
my @colors = values %fruit_colors;
print @fruits;
print @colors;
Codepad链接: http://codepad.org/vDVAxJcp
fruit_color
,但引用的是fruit_colors
(注意结尾的S)。use warnings;
use strict;
Global symbol "%fruit_colors" requires explicit package name at C:\temp\test.pl line 4.
Global symbol "%fruit_colors" requires explicit package name at C:\temp\test.pl line 5.
use strict;
use warnings;
其次,您有一个错别字(如果您使用了严格模块,则更容易发现)。
哇,你们这些人真快。
正如其他人所说:
use warnings
和use strict
,你就会得到一个错误消息,告诉你有关错误的信息。有很多技巧可以编写易读且相对无错的Perl代码。例如,我不在变量名中使用复数形式。因此,如果是“水果”或“水果”,我知道它应该是“水果”。我也倾向于通过使用术语“fruitColorHash”而不是“FruitColorList”来说出我的数据类型的名称,即使(驼峰式大小写已经过时,但我是一个固执己见的老开发人员)。
Damian Conway的书《Perl最佳实践》是一本优秀的书,将帮助您学习所有那些技巧和提示,将帮助您避免像这样的问题。事实上,这本书被认为是良好Perl编程的基石,现在有一个完整的部分专门介绍Damian Conway的书,称为Perlstyle,以及一个名为tidyperl的程序,将帮助重新格式化并指出不遵循Conway示例的地方。
所以,去看看Perldoc中的最佳实践部分(你知道关于perldoc
文档吗?输入命令perldoc
看看你会得到什么),并吸收那里放置的知识。然后拿到Conway的书。
use warnings;
use strict;
你打错字了:
my %fruit_color = ("apple", "red", "banana", "yellow");
应该是
my %fruit_colors = ("apple", "red", "banana", "yellow");