Hi everyone,
My script is giving an error message:
Can't call method "set" on unblessed reference at ./oop-closures-objects line 9.
I can't find the reason, @INC is updated, the name of a module is Student.pm. It seems maybe the problem in a variable $access_type? But I can't find the answer, I'll be happy in any kind of a help-messages :-)
Code of package is:
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;
# $data still available here
}
elsif ($access_type eq "get") {
return $data->{$key};
}
elsif ($access_type eq "keys") {
return (keys %{$data});
}
elsif ($access_type eq "destroy") {
$students--;
return $students;
}
else {
die "Access type should be set or get";
}
print "New student created, we have ",
++$students, " students.\n";
bless ($ref, $class);
# bless anonymous subroutine
}
} # End constructor
sub set {
my ($self, $key, $value) = @_;
# $self reference anonymous sub
$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";
}
sub DESTROY {
my $self = shift;
print "Object going out of scope:\n";
print "Students remain: ", $self->("destroy"), "\n";
}
1;
Code of a program that uses the Student.pm:
#!/usr/bin/perl -w
use lib("lib");
use Student;
$ptr1 = Student->new(); # Create new students
$ptr2 = Student->new();
$ptr3 = Student->new();
$ptr1->set("Name", "Jody Rogers"); # Set data for object
$ptr1->set("Major", "Law");
$ptr2->set("Name", "Christian Dobbins");
$ptr2->set("Major", "Drama");
$ptr3->set("Name", "Tina Savage");
$ptr3->set("Major", "Art");
$ptr1->display(); # Get all data for object
$ptr2->display();
$ptr3->display();
print "\nThe major for ", $ptr1->get("Name"),
" is ", $ptr1->get("Major"), ".\n\n";