Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Replacing objects

by dcmertens (Scribe)
on Dec 18, 2013 at 19:27 UTC ( [id://1067684]=note: print w/replies, xml ) Need Help??


in reply to Replacing objects

You're looking for the bless operator/command/function/whatever it's called:

bless $change, 'NewObj';

The ability to change an object's class at runtime is pretty powerful and can be used for mock objets, for example. However, you should only do this if you are sure that the internal storage is compatible.

Replies are listed 'Best First'.
Re^2: Replacing objects
by AnomalousMonk (Archbishop) on Dec 18, 2013 at 20:19 UTC
    ... you should only do this if you are sure that the internal storage is compatible.

    As an illustration of this important point, consider:

    >perl -wMstrict -le "use 5.014; ;; package Foo { sub new { return bless { fooble => 'wonkem' }; } sub mungeit { my $self = shift; my ($m) = @_; return $self->{fooble} .= $m; } } ;; package Bar { sub new { return bless { fooble => 1729 }; } sub mungeit { my $self = shift; my ($m) = @_; return $self->{fooble} += $m; } } ;; my $foo_obj = Foo->new; my $bar_obj = Bar->new; ;; print $foo_obj->mungeit('zoot'); print $bar_obj->mungeit(42); ;; bless $foo_obj, 'Bar'; ;; print $foo_obj->mungeit('zonk'); " wonkemzoot 1771 Argument "zonk" isn't numeric in addition (+) at -e line 1. Argument "wonkemzoot" isn't numeric in addition (+) at -e line 1. 0

    trizen: In fact, the whole business of re-bless-ing an object into another class is highly suspicious. Is this an instance of an XY Problem? What are you really trying to do?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1067684]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-24 22:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found