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",$key,$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,$key,$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.

 

你可能感兴趣的:(object,闭包,对象,closure,perl)