2011年10月20日 星期四

利用state 宣告變數使變數可以存入值的狀態

NOTE:記得use v5.010才能使用state敘述




#state.pl



use v5.010;
sub function{
    state $var= 0;
    $var++;
    print "Now \$var state is :",$var,"\n";
}


&function
&function
&function



#輸出結果:

hello $n now is :1
hello $n now is :2
hello $n now is :3
_______________________________________

#state.pl



use v5.010;
sub function{
    my $var= 0;
    $var++;
    print "Now \$var state is :",$var,"\n";
}


&function
&function
&function



#輸出結果:

hello $n now is :1
hello $n now is :1
hello $n now is :1


  • state EXPR
  • state TYPE EXPR
  • state EXPR : ATTRS
  • state TYPE EXPR : ATTRS
    state declares a lexically scoped variable, just like my does. However, those variables will never be reinitialized, contrary to lexical variables that are reinitialized each time their enclosing block is entered.
    state variables are enabled only when the use feature "state" pragma is in effect. See feature.



沒有留言:

張貼留言