Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading '=' in Perl

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 using tie(), not overload - 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.

like image 893
tjwrona1992 Avatar asked Aug 10 '15 14:08

tjwrona1992


Video Answer


1 Answers

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();
like image 71
ikegami Avatar answered Nov 15 '22 11:11

ikegami