Perl 面向对象的真正意思

cat RegularEmployee.pm 
package RegularEmployee;
sub new {
 my ($name,$age,$starting_position,$monthly_salary)=@_;
 my $r_employee = {
 "name" =>$name,
 "age" =>$age,
 "position" => $starting_position,
 "monthly_salary" => $monthly_salary,


jrhmpt01:/root/obj# cat RegularEmployee.pm 
package RegularEmployee;
sub new {
 my ($name,$age,$starting_position,$monthly_salary)=@_;
 my $r_employee = {
 "name" =>$name,
 "age" =>$age,
 "position" => $starting_position,
 "monthly_salary" => $monthly_salary,
 "months_worked" =>0,
};
 bless $r_employee,'RegularEmployee';
 return $r_employee;  ##返回对象的引用

sub promote{
my $r_employee=shift;
my $var=shift;
return $var;
}

       1;


jrhmpt01:/root/obj# cat a1.pl 
unshift(@INC,"/root/obj");  
require RegularEmployee;  
use Data::Dumper;  
$emp1=RegularEmployee::new('John Doe',32,  'Software Engineer',5000);

 my $xx= Dumper($emp1);    
print "111111111
";
print $xx;    
print "
";

$yy=$emp1->promote('20');
print "222222222222
";
print $yy;
print "
";

jrhmpt01:/root/obj# perl a1.pl 
111111111
$VAR1 = bless( {
                 'months_worked' => 0,
                 'monthly_salary' => 5000,
                 'position' => 'Software Engineer',
                 'name' => 'John Doe',
                 'age' => 32
               }, 'RegularEmployee' );

222222222222
120



$emp1=RegularEmployee::new('John Doe',32,  'Software Engineer',5000);

当Perl 看到$emp1->promote()时,它会决定$emp1 属于哪个类(也就是在其中执行bless的)

在这里,它是RegularEmployee.Perl于是就会如下所示调用这个函数

RegularEmployee::promote($emp1) 换句话说,箭头左边的对象只是作为相应子程序的第一个参数。

测试例子:

原文地址:https://www.cnblogs.com/hzcya1995/p/13351095.html