【问题标题】:What mistake am I making in this Perl code? [closed]我在这个 Perl 代码中犯了什么错误? [关闭]
【发布时间】:2011-06-20 22:00:56
【问题描述】:

我试过这段代码。这是行不通的。我在输出时没有得到任何结果。我犯了什么错误?

my %fruit_color = ("apple", "red", "banana", "yellow");
my @fruits = keys %fruit_colors;
my @colors = values %fruit_colors;
print @fruits;
print @colors;

键盘链接:http://codepad.org/vDVAxJcp

【问题讨论】:

标签: perl hash


【解决方案1】:

您声明 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.

【讨论】:

  • 愚蠢的错误 :P 感谢您的快速回复 :)
【解决方案2】:

第一个错误是第一行没有:

use strict;
use warnings;

其次,你有一个错字(如果你一直使用 strict 模块会更容易发现)。

【讨论】:

    【解决方案3】:

    伙计,你们的速度很快。

    正如其他人所说:

    • 您使用一个名称创建了一个列表,但随后又引用了另一个名称。
    • 如果您使用了use warningsuse strict,您会收到一条错误消息,告诉您该错误。

    编写清晰且相对无错误的 Perl 代码有很多提示和技巧。例如,我不在变量名中使用复数。因此,如果是“水果”或“水果”的问题,我知道应该是“水果”。我也倾向于使用诸如“fruitColorHash”与“FruitColorList”之类的术语来说出我的数据类型的名称,即使(Camel Casing isNotInStyleAnyMore,但随后是 Im_an_old_grouchy_developer_who_is_set_in_his_ways)。

    Damian Conway 的书Perl Best Practices 是一本出色的书,可帮助您了解所有这些技巧和技巧,从而帮助您避免此类问题。事实上,这本书被认为是优秀 Perl 编程的试金石,现在有一整节专门介绍 Damian Conway 的书,名为 Perlstyle,还有一个名为 tidyperl 的程序将帮助重新格式化并指出不适合的地方遵循康威的例子。

    所以,继续查看 Perldoc 中的“最佳实践”部分(您知道 perldoc 文档,不是吗?输入命令 perldoc 看看您会得到什么)并吸收那里的知识进去。然后去拿康威的书。

    【讨论】:

      【解决方案4】:

      你的代码中有一个错字,如果你有的话你会注意到的:

      use warnings;
      use strict;
      

      在您的代码中。你总是应该这样做的。

      【讨论】:

        【解决方案5】:

        你有一个错字:

        my %fruit_color = ("apple", "red", "banana", "yellow");
        

        应该是

        my %fruit_colors =  ("apple", "red", "banana", "yellow");
        

        【讨论】:

          猜你喜欢
          • 2016-12-09
          • 1970-01-01
          • 1970-01-01
          • 2021-06-23
          • 1970-01-01
          • 1970-01-01
          • 2019-10-07
          • 2017-10-12
          • 1970-01-01
          相关资源
          最近更新 更多