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

Re: Replacing objects

by dcmertens (Beadle)
on Dec 18, 2013 at 19:27 UTC ( #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 (Canon) 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
Node Status?
node history
Node Type: note [id://1067684]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2016-12-10 08:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (160 votes). Check out past polls.