加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl closure object闭包和对象

发布时间:2020-12-15 21:01:30 所属栏目:大数据 来源:网络整理
导读:[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) = @_; ???????

[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:%-20sn",$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"),".nn";
[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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读