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!


In reply to Re: Overloading assignment by v_o_i_d
in thread Overloading assignment by v_o_i_d

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.