- #!/usr/bin/perl -w
-
#
-
use strict;
-
-
my @name;
-
-
&greet("jo");
-
&greet("hu");
-
&greet("liu");
-
-
sub greet{
-
my ($str) = @_;
-
if(not @name){
-
print "Hi $str! You are the firest on here!\n";
-
}else{
-
print "Hi $str! $name[-1] is also here!\n";
-
}
-
push @name, $str;
-
}
Hi jo! You are the firest on here!
Hi hu! jo is also here!
Hi liu! hu is also here!
use state
- use 5.010;
-
greet( 'Fred' );
-
greet( 'Barney' );
-
greet( 'Wilma' );
-
greet( 'Betty' );
-
sub greet {
-
state @names;
-
my $name = shift;
-
print "Hi $name! ";
-
if( @names ) {
-
print "I've seen: @names\n";
-
}
-
else {
-
print "You are the first one here!\n";
-
}
-
push @names, $name;
-
}
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!
阅读(612) | 评论(0) | 转发(0) |