- 论坛徽章:
- 0
|
package Student;
sub new
{
my $class = shift;
my $data={};
our $students;
my $ref = sub
{
my ($access_type, $key, $value)=@_;
if ($access_type eq "set")
{
$data->{$key} = $value;
}
elsif ($access_type eq "get")
{
return $data->{$key};
}
elsif ($access_type eq "keys")
{
return keys %{$data};
}
elsif ($access_type eq "destory")
{
$students--;
return $students;
}
else
{
die "Access type should be set or get\n";
}
print "New Student created, we have ",++$students," students.\n";
bless ($ref, $class);
}
}
sub set{
my ($self, $key, $value) = @_;
$self->("set", $key, $value);
}
sub get{
my ($self, $key) = @_;
$self->("get", $key);
}
sub display{
my $self = shift;
my @keys = $self ->("key");
foreach my $key(@keys)
{
my $value = $self->("get", $key);
print "%-25s%-5s:%-20s\n", $self, $key, $value;
}
print "\n";
}
sub DESTROY{
my $self = shift;
print "Object going out of scope:\n";
print "Students remain: ", $self->("destroy"), "\n";
}
1;
------------------------------------------------------------
#!/usr/bin/perl
use Student;
use warnings;
use strict;
my $ptr1 = Student->new();
my $ptr2 = Student->new();
my $ptr3 = Student->new();
$ptr1->set("Name", "Jody Rogers");
$ptr1->set("Major", "Law");
$ptr2->set("Name", "Christian Dobbins");
$ptr2->set("Major", "Drama");
$ptr3->set("Name", "Tina Savage");
$ptr3->set("Major", "Art");
$ptr1->display();
$ptr2->display();
$ptr3->display();
print "\nThe major for ", $ptr1->get("Name")," is ", $ptr1->get("Major"), ".\n\n";
这个例子是 <perl 实例精解第四版> 的
在执行的时候老是报错
Can't call method "set" on unblessed reference at student_pm.pl line 10.
那个大拿帮看看!!感激不尽!! |
|