--- James Edward Gray II <[EMAIL PROTECTED]> wrote:
> If I have an object and I want to increase it's functionality by
> "upgrading/promoting" it to a subclass if certain conditions are met
> during a method call, could/should I use something like:
>
> sub some_method {
> my $self = $_[0];
>
> # ...
>
> if (PROMOTE_CONDITION) {
> $_[0] = Subclass->copy_constructor($self);
> }
> }
>
> That will change the reference in the calling code, right? Any reason
> I shouldn't do this?
>
> James
As for whether or not you should do that, it really depends upon what you're trying to
do and
since I don't know what that is, I can't comment.
You are correct that the above code will work. However, since this *is* a reference,
you don't
need to worry about keeping @_ intact. bless affects the reference and leaves the
referent
intact. Here's a little test script that demonstrates how this works.
-----------
#!/usr/bin/perl -w
use strict;
package Foo;
sub new {
bless { this => 1 }, shift;
}
sub promote {
my $self = shift;
$self = Foo::Bar->copy_constructor( $self );
}
sub inherited_method {
print "Houston, we have inheritance!\n";
}
package Foo::Bar;
use base 'Foo';
sub copy_constructor {
my ( $class, $object ) = @_;
bless $object, $class;
}
sub not_in_parent {
print "We're ok!\n";
}
package main;
use Data::Dumper;
my $object = Foo->new;
eval { $object->not_in_parent };
print "\nWarning: $@\n";
$object->promote;
$object->not_in_parent;
$object->inherited_method;
print Dumper $object;
-----------
Cheers,
Ovid
=====
"Ovid" on http://www.perlmonks.org/
Someone asked me how to count to 10 in Perl:
push@A,$_ for reverse q.e...q.n.;for(@A){$_=unpack(q|c|,$_);@a=split//;
shift@a;shift@a if $a[$[]eq$[;$_=join q||,@a};print $_,$/for reverse @A
__________________________________________________
Do you Yahoo!?
Faith Hill - Exclusive Performances, Videos & More
http://faith.yahoo.com
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]