I imagined the second solution:
my $obj = 'Parent'->new;
$obj->populate(@data);
for my $child_class (@possible_child_classes) {
if (my $new = $child_class->new_from_parent($obj)) {
$obj = $new;
last
}
}
# Don't forget to handle the case that $obj hasn't changed.
In fact, the only problem why this shouldn't go to the parent class is the array of possible child classes. So, get it from outside; the parent can insist on its children implementing a method:
sub new_from_parent { die "Should be overriden.\n" }
sub rebless {
my $self = shift;
my @possible_child_classes = @_;
for my $child_class (@possible_child_classes) {
# etc. using $self instead of $obj.
And the code becomes
my $obj = 'Parent'->new;
$obj->populate(@data);
$obj->rebless(@possible_child_classes);
|