Perl 持久化私有变量

2021-07-05  本文已影响0人  PETJO

9. 持久化私有变量

sub marine {
    my $n += 1;    #每次调用子程序时,私有变量都会被重新定义
    print "Hello, sailor number $n!\n";
}

&marine;
&marine;
&marine;
&marine;
&marine;


use v5.10;

sub marine {
    state $n += 1;    # state 声明持久化私有变量
    print "Hello, sailor number $n!\n";
}

# 任意类型的变量都可以被 state 声明
&running_sum(5, 6);
&running_sum(1..3);
&running_sum(4);

sub running_sum {
    state $sum = 0;    # state声明标量变量
    state @numbers;    # state声明数组变量

    foreach my $number (@_) {
        push @numbers, $number;
        $sum += $number;
    }

    say "The sum of (@numbers) is $sum";
}
上一篇下一篇

猜你喜欢

热点阅读