[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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。