- 论坛徽章:
- 0
|
请帮忙分析一下,紫色部分的1;是什么作用,另外代码二为什么运行会报如下错误
Can't call method "set" on unblessed reference at /tmp/hjb17.pl line 9.-
- 1
- 2 package Student;
- 3 sub new { # Constructor
- 4 my $class = shift;
- 5 my $data={};
- 6 our $students;
- 7 my $ref = sub { # Closure
- 8 my ($access_type, $key, $value) = @_;
- 9 if ($access_type eq "set"){
- 10 $data->{$key} = $value; # $data still available here
- 11 }
- 12 elsif ($access_type eq "get"){
- 13 return $data->{$key};
- 14 }
- 15 elsif ($access_type eq "keys"){
- 16 return (keys %{$data});
- 17 }
- 18 elsif ($access_type eq "destroy"){
- 19 $students--;
- 20 return $students;
- 21 }
- 22 else{
- 23 die "Access type should be set or get";
- 24 }
- 25 print "New student created, we have ", ++$students,
- 26 " students.\n";
- 27 bless ($ref, $class); # bless anonymous subroutine
- 28 }
- 29 } # End constructor
- 30 sub set{
- 31 my($self,$key,$value) = @_; # $self references anonymous sub
- 32 $self->("set",$key,$value);
- 33 }
- 34 sub get{
- 35 my ($self,$key) = @_;
- 36 return $self->("get", $key);
- 37 }
- 38 sub display{
- 39 my $self = shift;
- 40 my @keys = $self->("keys");
- 41 @keys=reverse(@keys);
- 42 foreach my $key (@keys){
- 43 my $value = $self->("get",$key);
- 44 printf "%-25s%-5s:%-20s\n",$self, $key,$value ;
- 45 }
- 46 print "\n";
- 47 }
- 48 sub DESTROY{
- 49 my $self = shift;
- 50 print "Object going out of scope:\n";
- 51 print "Students remain: ", $self->("destroy"), "\n";
- 52 }
- 53 [color=Magenta]1;[/color]
- [code]
- 1 #!/usr/bin/perl
- 2 use Student;
- 3 $ptr1 = Student->new(); # Create new students
- 4 $ptr2 = Student->new();
- 5 $ptr3 = Student->new();
- 6 print "$ptr1\n";
- 7 print "$ptr2\n";
- 8 print "$ptr3\n";
- 9 $ptr1->set("Name", "Jody Rogers"); # Set data for object
- 10 $ptr1->set("Major", "Law");
- 11 $ptr2->set("Name", "Christian Dobbins");
- 12 $ptr2->set("Major", "Drama");
- 13 $ptr3->set("Name", "Tina Savage");
- 14 $ptr3->set("Major", "Art");
- 15 $ptr1->display(); # Get all data for object
- 16 $ptr2->display();
- 17 $ptr3->display();
- 18 print "\nThe major for ", $ptr1->get("Name")," is ", $ptr1->get("Major"), ".\n\n";
复制代码 |
|