I have done what you said. Here is the code...
Simple class example for demonstration purposes:
#---Sample.pm---
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..
#----code.pl----
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 code.pl line 28.
Argument " bishop" isn't numeric in addition (+) at code.pl 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! |