perl closure object闭包和对象

[root@dou shili]# cat Student.pm
package Student;
sub new { # Constructor
        my $class = shift;
        my $data = {};
        our $students;
        my $ref = sub { # Closure
                my($access_type,$key,$value) = @_;
                if($access_type eq "set") {
                        $data->{$key} = $value;
                        if($key eq "Name") {
                                ++$students;
                                print "New student created.we have ",$students," students.\n";
                        }
                }
                elsif($access_type eq "get") {
                        return $data->{$key};
                }
                elsif($access_type eq "keys") {
                        return (keys %{$data});
                }
                else {
                        die "Access type should be set or get";
                }
        };
                bless($ref,$class);
                #return $ref;
}# end constructor
sub set {
        my $self = shift;
        my($key,$value) = @_;
        $self->("set",$value);
}
sub get {
        my($self,$key) = @_;
        return $self->("get",$key);
}
sub display {
        my $self = shift;
        my @keys = $self->("keys");
        @keys = reverse(@keys);
        foreach my $key (@keys) {
                my $value = $self->("get",$key);
                printf "%-25s%-5s:%-20s\n",$self,$value;
        }
        print "\n";
}
1;
[root@dou shili]# cat useStudent.pl
#!/usr/bin/perl -w
use strict;
use Student;

my $prt1 = Student->new();
my $prt2 = Student->new();
my $prt3 = Student->new();

$prt1->set("Name","Tomcat");
$prt1->set("Major","Math");
$prt2->set("Name","Oracle");
$prt2->set("Major","American");
$prt3->set("Name","Hello");
$prt3->set("Major","World");
$prt1->display();
$prt2->display();
$prt3->display();
print "\nThe major for ",$prt1->get("Name"),"is ",$prt1->get("Major"),".\n\n";
[root@dou shili]# perl useStudent.pl
New student created.we have 1 students.
New student created.we have 2 students.
New student created.we have 3 students.
Student=CODE(0x160e53d0) Name :Tomcat
Student=CODE(0x160e53d0) Major:Math

Student=CODE(0x1610af20) Name :Oracle
Student=CODE(0x1610af20) Major:American

Student=CODE(0x1610b030) Name :Hello
Student=CODE(0x1610b030) Major:World

The major for Tomcatis Math.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...