Since simply overloading '='
in Perl does not act as one would expect, what is the proper way to do this?
Quote from overload perldoc:
Simple assignment is not overloadable (the
'='
key is used for the Copy Constructor). Perl does have a way to make assignments to an object do whatever you want, but this involves usingtie()
, notoverload
- see tie and the COOKBOOK examples below.
I have read through the COOKBOOK and the documentation for tie and am having trouble figuring out how you could use it in this way.
I want to be able to create an object like so: my $object = Object->new()
Then when I assign it to something I want it to do some special processing.
For example: $object = 3
would internally do something like $object->set_value(3);
I know this isn't necessarily good practice. This is more of an educational question. I just want to know how this can be done. Not whether it should be done.
You can't do that. You can add magic to a variable so that a sub is called after a value is assigned to the variable, but that's a far cry from what you asked.
Besides, what you asked doesn't really make sense. What should the following do?
my $object;
$object = Object->new();
$object = Object->new();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With