Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Moose parent class cast with child

Tags:

oop

perl

moose

package Point;
use Moose;

has 'x' => (isa => 'Int', is => 'rw');
has 'y' => (isa => 'Int', is => 'rw');

package Point3D;
use Moose;

extends 'Point';

has 'z' => (isa => 'Int', is => 'rw');

package main;

use Data::Dumper;

my $point1 = Point->new(x => 5, y => 7);
my $point3d = Point3D->new(z => -5);

$point3d = $point1;
print Dumper($point3d);

Is it possible to cast a parent to child class such as c++? In my examble is $point3d now a Point and not a Point3D include the Point.

like image 523
xGhost Avatar asked Feb 26 '23 11:02

xGhost


2 Answers

Take a look at the Class::MOP documentation on CPAN, especially the clone_object and rebless_instance methods:

sub to_3d {
  my ($self, %args) = @_;
  return Point3D->meta->rebless_instance(
    $self->meta->clone_object($self),
    %args,
  );
}

And then use it like the following:

my $point_3d = $point->to_3d(z => 7);

This will also take care to treat the newly specified %args as if they've been passed in by the constructor. E.g. builders, defaults, and type constraints are all considered during this build.

like image 200
phaylon Avatar answered Mar 07 '23 03:03

phaylon


You do not need to cast in Perl, since it is a dynamic language. In your case though, the variable $point3d contains a reference to a Point object at the end of the script. You cannot treat this as a Point3D because it is not a Point3D. You could manually convert it, but you can't "remake" an existing object as a different class. (Well, you theoretically can in Perl, but you shouldn't.)

like image 37
cdhowie Avatar answered Mar 07 '23 04:03

cdhowie