On Thu, Nov 14, 2002 at 12:19:47PM +0000, Andy Wardley wrote:
> Can we overload + in Perl 6 to work as both numeric addition
> and string concatenation, depending on the type of the operand
> on the left?
>
> I realise the answer is "probably not", given the number/string
> ambiguity of Perl variables:
>
> my $a = 123;
> my $b = 456;
> $a + $b; # 579 or 123456?
Its worse than that, what does this do:
sub add ($num1, $num2) {
return $num1 + $num2;
}
add($foo, $bar);
There are obvious simple cases
$foo = 23; $bar = 42; (perl can figure this one out easy)
$foo = "foo"; $bar = "bar"; (perl can figure ditto)
but it rapidly gets ambiguous
$foo = 23; $bar = 'bar';
$foo = '23'; $bar = 42;
so maybe you can solve it with types:
sub add (number $num1, number $num2) {
...
}
but what about this very simple case:
# We read in from a file, so should Perl consider them
# strings or numbers?
@numbers = slurp 'number_file'; chomp @numbers;
$total = $numbers[0] + $numbers[1];
then you have to do something like this:
number @numbers = slurp 'number_file'; chomp @numbers;
$total = $numbers[0] + $numbers[1];
and I really, really, really don't want to even have to think about types
for basic tasks.
No matter what you decide 23 + 'bar' should do (should it concat? should it
add? should it be an error?) it will be wrong to 2/3 of the population
because the add/concat idea violates the cardinal rule of overloading:
Don't make the same op do two different things.
While people might think string concatination is the same as numeric
addition, its really quite a different operation. If we were to try and
make + do similar things for both it would either be:
23 + 42 == 64;
'a' + 'c' == 'd';
or
'a' + 'c' == 'ac';
23 + 42 == 2342;
If you find yourself having to decide between two radically different
behaviors when a binary op is presented with two different types, something
is wrong.
The real question is: should adding two strings to anything at all?
And the real question below that one is: how far should type coercion go?
In Perl 5 it stops at a sane point:
$ perl -wle 'print "bar" + "foo"'
Argument "foo" isn't numeric in addition (+) at -e line 1.
Argument "bar" isn't numeric in addition (+) at -e line 1.
0
Ok, so string + string does something almost as odd as C does, but at least
it warns about it. And that's probably a good default way to handle it.
<copout type=standard>And you can always just change the behavior of
strings in a module.</copout>
--
Michael G. Schwern <[EMAIL PROTECTED]> http://www.pobox.com/~schwern/
Perl Quality Assurance <[EMAIL PROTECTED]> Kwalitee Is Job One
Monkey tennis