perl 永远看不懂的对象、类及方法
类方法:传递给类方法的第一个参数是隐藏的,是->符号左边的字符串(即类名)。实例方法:传递给实例方法的第一个参数也是隐藏的,是->符号左边的字符串(一个引用或叫做一个对象)。
最常用的类方法是:constructor function(构造函数)。
# cat House.pm
#!/usr/bin/perl
package House;
use warnings;
use strict;
sub new {
my $class = shift; #Constructor method
my $ref = { }; #Create a reference
bless($ref,$class); #Create the object with bless function
return $ref; #Return a reference to the object
}
sub set_data {
my $self = shift; #Access or instance methods
$self->{key} = shift; #Assign or store the object's attributes
}
sub get_data {
my $self = shift;
return $self->{key}; #Get or fetch the object's attributes
}
1;
# clear
# cat House.pm
#!/usr/bin/perl
package House;
use warnings;
use strict;
sub new {
my $class = shift; #Constructor method
my $ref = { }; #Create a reference
bless($ref,$class); #Create the object with bless function
return $ref; #Return a reference to the object
}
sub set_data {
my $self = shift; #Access or instance methods
$self->{key} = shift; #Assign or store the object's attributes
}
sub get_data {
my $self = shift;
return $self->{key}; #Get or fetch the object's attributes
}
1;
# cat useHouse.pl
#!/usr/bin/perl -w
use strict;
use House;
my $arg1 = "hello";
my $arg2 = "stillhello";
my $obj1 = House->new; # Create the object;a reference is returned
my $obj2 = House->new;# Create another house object.
$obj1->set_data($arg1); # Store or assign data to the object
my $result1 = $obj1->get_data; # Fetch data from the object
print "The result1 is $result1\n";
$obj2->set_data($arg2); # Store or assign data to the object
my $result2 = $obj2->get_data; # Fetch data from the object
print "The result2 is $result2\n";
# perl useHouse.pl
The result1 is hello
The result2 is stillhello
在引用中给对象添加属性:并使用ref判断对象属于哪个package。
# cat Hh.pm
#!/usr/bin/perl
package Hh;
use warnings;
use strict;
sub new {
my $class = shift;
my $ref = { owner => shift,
country => shift,
};
bless($ref,$class);
return $ref;
}
1;
# cat useHh.pl
#!/usr/bin/perl -w
use strict;
use Hh;
my $arg1 = "aobama";
my $arg2 = "America";
my $ref = Hh->new($arg1,$arg2);
my $owner = $ref->{owner};
my $country = $ref->{country};
print "The owner of the house is $owner\n";
print "The location of the house is $country\n";
print "The object \$ref belongs to package ref($ref)\n";
# perl useHh.pl
The owner of the house is aobama
The location of the house is America
The object $ref belongs to package ref(Hh=HASH(0x1344e2a0))
最后一句显示对象属于package Hh。
页:
[1]