"无法在未定义的值上调用方法'状态'"?

Raj*_*Raj -1 perl

我是perl的新人.我正在从一本书中学习,其中一个例子就在那里.我无法找到问题所在.

use 5.010;
greet( 'Fred' );
greet( 'Barney' );
sub greet {
    state $last_person;
    my $name = shift;
    print "Hi $name! ";
    # This is the error line:
    if( defined $last_person ) {   
       print "$last_person is also here!\n";
    } else {
       print "You are the first one here!\n"
    }
    $last_person = $name;
}
Run Code Online (Sandbox Code Playgroud)

它在ch4_3.pl上的未定义值上给出了"无法调用方法"状态的错误.

zou*_*oul 8

也许该state功能未启用?引用文档:

仅当使用功能"state"pragma生效时才启用状态变量,除非关键字写为CORE :: state.另见功能.或者,将v5.10或更高版本包含在当前作用域中.

正如我在评论中所读到的那样,你没有包括这个use 5.010实用语.我认为这就是问题所在.没有它,我的Perl(5.18.2,和你的一样)抱怨同样的错误.

  • @Raj - "使用5.010"意味着"打开5.10中被认为是稳定的所有功能"(我个人更喜欢语法`use v5.10`)而不是"仅适用于Perl 5.10而不是更新". (3认同)