Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: Overloading assignment

by v_o_i_d (Novice)
on Oct 26, 2004 at 06:39 UTC ( #402479=note: print w/replies, xml ) Need Help??

in reply to Overloading assignment

I have done what you said. Here is the code...
Simple class example for demonstration purposes: package Sample; use warnings; use strict; use overload( '+' => \&add, fallback => 1, ); sub TIESCALAR { my $class = shift; my $self = { data => [@_], }; bless( $self, $class ); return $self; } sub add { $_ .= $_[1] foreach( @{$_[0]->{data}} ); } sub STORE { @{$_[0]->{data}} = (ref( $_[1] ) eq 'ARRAY') ? @{$_[1]}: ($_[1]); } sub FETCH { return $_[0]; } 1; #---------------
Next is the program.. use warnings; use strict; use Sample; my $var1; my $var2 = tie( $var1, 'Sample', 'black', 'white' ); # The assigment test... #$var1 = 'green'; #$var2 = ['green','red']; # The overload test... #$var1 + ' bishop'; #$var2 + ' bishop'; #print ref($var2),"\n"; print join( "\n", @{$var2->{data}} ); exit 0; #---------------
Compiler warnings/errors: (addition operation on the tie() variable $var1)
Useless use of addition (+) in void context at line 28. Argument " bishop" isn't numeric in addition (+) at line 28.
* The returned variable $var2 however, will cause the 1st warning but successfully calls the 'addition' Sample::add.

The opposite works with assignment:
$var2 = ['green','red'] destroys the class instance of Sample and becomes an array reference. $var1 = ['green','red'] works as it should because of tie()!

Both operations don't work on the same variable, $var1 can't do the addition + and $var2 can't do the assignment!

Replies are listed 'Best First'.
Re^2: Overloading assignment
by Zaxo (Archbishop) on Oct 27, 2004 at 08:18 UTC

    Both your tie class and the overloaded add are not quite correct.

    The FETCH routine does not return a scalar of the expected kind. You have it returning a reference to the underlying hash, rather than some scalar data stored in it.

    An overridden operator like '+' is written like a constructor. It should take data from its arguments and return a new object of the correct type constructed from the result. What you have written for add is a mutator which behaves more like '.=' than '+'. It is a good idea to make sure overridden operators are as much like the builtins as possible.

    I'm not sure there is a way to make a tied variable honor the underlying classes' operator overrides. I wasn't aware of that, but my attempts to make it happen have failed.

    After Compline,

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (11)
As of 2021-09-22 08:46 GMT
Find Nodes?
    Voting Booth?

    No recent polls found