Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
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.


Comment on Re: Replacing objects
Select or Download Code
Re^2: Replacing objects
by AnomalousMonk (Abbot) 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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (12)
As of 2014-12-22 22:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (132 votes), past polls