为什么这个来自“学习Perl第6版”的第4章示例无法运行?

3

我在《学习Perl第六版》的第78页上卡住了第4章练习4。我从第301页复制了问题的代码示例。我正在使用Ubuntu 11.04上的Perl版本5.10.1。我得到了无法解决的错误,有人可以帮忙吗?我将在下面列出代码和错误消息。

#!/usr/bin/perl -w
use strict;

greet( 'Fred' );
greet( 'Barney' );

sub greet {
  state $last_person;

  my $name = shift;

  print "Hi $name! ";

  if( defined $last_person ) {
      print "$last_person is also here!\n";
 }
  else {
      print "You are the first one here!\n";
}
  $last_person = $name;
}


Global symbol "$last_person" requires explicit package name at ./ex4-4 line 8.
Global symbol "$last_person" requires explicit package name at ./ex4-4 line 14.
Global symbol "$last_person" requires explicit package name at ./ex4-4 line 15.
Global symbol "$last_person" requires explicit package name at ./ex4-4 line 20.
Execution of ./ex4-4 aborted due to compilation errors.
3个回答

9

您需要在脚本顶部写入 use feature 'state' 以启用 state 变量。请参阅 perldoc -f state


或者使用5.01n;,其中n为{0, 2, 4}。 - Axeman
谢谢你抽出时间来帮助我。我应该输入"use 5.010;"而不是"use strict;"。在书中,我混淆了这两个。 - David

6

根据手册

从perl 5.9.4开始,您可以使用state关键字声明变量,而不是my。但是,为了使其正常工作,您必须事先启用该功能,可以通过使用feature pragma或在单行代码中使用-E来实现(请参见feature)。


你还可以使用use 5.010use 5.10.0,它会隐式激活Perl该版本中所有可用的功能。 - cjm
你的第77页,在练习之前的最后一个代码示例页面上显示了"use 5.010;"。现在我的程序可以正确运行了。我以为使用"use strict;"指令就足够了,但它没有起到任何作用。 - David

1

以前做这件事的方式是使用闭包:feature

{
    my $last_person;

    sub greet {

        my $name = shift;

        print "Hi $name! ",
          defined $last_person ? "$last_person is also here!"
                               : "You are the first one here!",
          "\n";

        $last_person = $name;
    }
}

在这个例子中,巧妙的say功能也会非常有用。


感谢您抽出时间来帮助我。正如上面指出的那样,通过使用“use 5.010;”编译指示,程序可以正常工作。我对您上面的代码示例绕过了(if)和(else)的方式非常感兴趣。我一定会尝试一下。谢谢。 - David

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接