develooper Front page | perl.perl5.porters | Postings from November 1999

Re: assignment overload [Was: [ID 19991101.002] Data::Dumper 2.101 and

From:
John Macdonald
Date:
November 10, 1999 18:58
Subject:
Re: assignment overload [Was: [ID 19991101.002] Data::Dumper 2.101 and
Message ID:
199911110230.VAA18296@elegant.com
Barrie Slaymaker <barries@slaysys.com> writes:
|| Larry Wall wrote, in part:
|| > 
|| > I don't know about assignment overloading
|| 
|| Me either :-).  Overloaded designs are tricky enough to begin 
|| with.
|| 
|| Without being able to overload assignment, you can build an
|| object that drives completely like a scalar with one subtle 
|| yet frequently encountered exception: assignment is shallow.

But what is the meaning of overloaded assignment?  In
particular, how do you distinguish between assigning a
new value to an object of a particular type from assigning
a typed value to a variable (thereby changing the type of
the variable)?  When you write:

    my $x = 1;        # $x has an integer value
    $x = 'abc';       # now it has a string value

you don't expect the second assignment to be affected by the
previous contents of $x.  The old contents are simply replaced
with the new contents *and its type*.

Overloading assignment only makes sense in a strongly typed
language.  It might be possible to enforce it for "my Dog $x"
perhaps, but when the target is not strongly typed, it would
require a separate operator, distinct from =, for it to be an
overloaded assignment that preserved the type of the target
and did any massaging necessary of the newly assigned value
to make it conform to that type.

While writing the book, I hit upon a trick to do a type-specific
assignment for one particular case.  I wanted a subroutine to
work when its argument might be an int or a BigInt or an
SSLeay::bn.  I needed to initialize a variable to 1, but for it
to be the same type as the argument, not an int.  The trick for
that was:

    my $product = $arg - $arg + 1;     # 1, but int/BigInt/etc: same as $arg

--
John Macdonald     jmm@jmm.pickering.elegant.com



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About