Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting types in OOP Perl program

Tags:

oop

casting

perl

I am experimenting with something I like to do in Perl but I am getting a strange output and I can't figure out why. Basically I have 2 classes. A is the base and B inherits from A. I issue prints to the screen to track the program and result. On the last stage I am trying to cast A Type to B Type and to use a function declared in B.

For some reason this whole program runs twice - the output is duplicated - though i run the program once. Is this a real issue? and why does it happen?

I am pasting here my code and output. The file name is A.pm; Running command: 'perl A.pm'

package A;


sub new
{
        my ($class) = shift;
        my $self = {};
        bless $self, $class;
}

sub P
{
        my $self = shift;
        print "P:A\n";
}

sub PA
{
        my $self=shift;
        print "PA:A\n";
}  
1;

###############################
package B;
use base 'A';

sub new
{
        my ($class) = shift;
        my $self = {};
        bless $self, $class;
}

sub P
{
        my $self=shift;
        print "P:B\n";
}

sub PB
{
        my $self=shift;
        print "PB:B\n";
}

1;
###############################

package main;

$o = B->new;
$o->P();
$o->PA();
$o->PB();
$o = A->new;
$o->P();
$o->PA();
print "Casting\n";
bless $o , 'B';
$o->PB();
print "End\n";

Output:

[#~]perl A.pm
P:B
PA:A
PB:B
P:A
PA:A
Casting
PB:B
End
P:B
PA:A
PB:B
P:A
PA:A
Casting
PB:B
End
like image 754
yanger Avatar asked Aug 24 '26 10:08

yanger


1 Answers

Instead of the deprecated base, do use parent -norequire => 'A';

One of the defects of base that caused it to be superseded by parent is that there's no good way to tell it not to try loading the base class module.

like image 105
ysth Avatar answered Aug 27 '26 08:08

ysth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!