Chinaunix首页 | 论坛 | 博客
  • 博客访问: 837402
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-10-09 16:44:32

  1. #!/usr/bin/perl -w
  2. #
  3. use strict;

  4. my @name;

  5. &greet("jo");
  6. &greet("hu");
  7. &greet("liu");

  8. sub greet{
  9.     my ($str) = @_;
  10.     if(not @name){
  11.         print "Hi $str! You are the firest on here!\n";
  12.     }else{
  13.         print "Hi $str! $name[-1] is also here!\n";
  14.     }
  15.     push @name, $str;
  16. }
Hi jo! You are the firest on here!
Hi hu! jo is also here!
Hi liu! hu is also here!

use state

  1. use 5.010;
  2. greet( 'Fred' );
  3. greet( 'Barney' );
  4. greet( 'Wilma' );
  5. greet( 'Betty' );
  6. sub greet {
  7.     state @names;
  8.     my $name = shift;
  9.     print "Hi $name! ";
  10.     if( @names ) {
  11.         print "I've seen: @names\n";
  12.         }
  13.     else {
  14.         print "You are the first one here!\n";
  15.         }
  16.     push @names, $name;
  17.     }
state EXPR
  • state TYPE EXPR
  • state EXPR : ATTRS
  • state TYPE EXPR : ATTRS

    declares a lexically scoped variable, just like does. However, those variables will never be reinitialized, contrary to lexical variables that are reinitialized each time their enclosing block is entered.

    variables are enabled only when the feature "state" pragma is in effect. See .


There’s a slight restriction on arrays and hashes as state variables, though. We can’t
initialize them in list context as of Perl 5.10:
state @array = qw(a b c); # Error!



阅读(575) | 评论(0) | 转发(0) |
0

上一篇:$#_

下一篇:Omitting the Ampersand

给主人留下些什么吧!~~