Interesting Use of State in Perl

还是来自«learning perl»中的例子。

  1. 写一个名为greet的子例程,当给定一个人名作为参数的时候,打出欢迎他的信息,并告诉他前一个来宾的名字。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use 5.010;
greet('Fred');
greet('Barney');

sub greet{
    state $last_person;

    my $name = shift;

    print "Hi, $name!";

    if (defined $last_person) {
        print "$last_person is also here!\n";
    }

    else {
        print "you are the first one here!\n";
    }

    $last_person = $name;
}

2.修改程序1, 告诉所有新来的人之前已经迎来了哪些人.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use Data::Dumper;
use 5.010;

greet('Fred');
greet('Barney');
greet('Wilma');
greet('Betty');

sub greet{
    state @before;

    my $name = shift;
    print "Hi, $name!";

    if (@before){
        print " I have seen @before\n";
    }
    else {
        print " you are the first one here!\n";
    }

    push @before, $name;
}