perl写子程序持久性私有变量state声明符报错的原因

来源:互联网 发布:python无限循环语句 编辑:程序博客网 时间:2024/06/05 03:42

学习perl子程序这一章,有一个习题是这样的:

写一个名为greet的子程序,给定人名作参数时,打印出欢迎信息,告诉所有新来人之前已经迎接了那些人:

例如:

greet("A");

greet("B");

greet("C");

按照语句的顺序,应该打印出:

Hi  A!You are the first one here!

Hi  B!   I have seen :A

Hi  C!   I have seen:A B


初次编写代码如下:

#!/usr/bin/perl -wuse strict;greet('A');greet('B');greet('C');sub greet{state @names;my $name = shift;print "Hi $name! ";if(@names){print "I have seen: @names\n";}else{print "You are the first one here!\n";}push @names,$name;}

这样会报错,提示列表量@names有错。

解决办法:第三行加入 use feature ‘state’,运行成功。



0 0