Can overloaded '+' return an array? If so, how?



The following sample code prints:

combine: result= [1 2 3 4]
main: ar = [4]

I expect it to print:

combine: result= [1 2 3 4]
main: ar = [1 2 3 4]

The issue is that "combine", which is the function that '+' maps to,
returns an array. When, in the main program, I say:

my @ar = $ca1 + ca2

I expect the "combine" function to be called in list context. But
evidently it is called in scalar context, because my @ar variable
receives the cardinality of the "result" array, rather than a copy of
the array.

Looking at Ch 13 of the Camel book, I don't see any restriction on
return values of overloaded operators; but maybe I'm just missing it.
If there's a way to do it, but I'm doing it wrong, I'd like to know
that. Either way, please advise.

(If, instead of what I do in the example, I return a reference to the
array, and alter my main routine correspondingly, then, of course,
everything works.)

Thanks,
-P.

Example:

====================
use strict;

my $ca1 = ClassAct->new( 1, 3 );
my $ca2 = ClassAct->new( 2, 4 );

my @ar = $ca1 + $ca2;
print "main: ar = [@ar]\n";

{
package ClassAct;

use overload (
'+' => "combine",
fallback => 1,
);

sub combine {
my $obj1 = shift;
my $obj2 = shift;
my @result = sort ( @{$obj1}, @{$obj2} );
print "combine: result= [@result]\n";
return @result;
};

sub new {
my $class = shift;
my $self = [
];
while( my $value = shift ) {
push @{$self}, $value;
}
bless $self, $class;
return $self;
}
}
====================

.



Relevant Pages

  • Re: Packages and returning errors
    ... > array intact. ... sub is_a_instance_method { ... my $class = shift; ... You need to fix the scope of $error by moving its declaration outside ...
    (comp.lang.perl.misc)
  • Re: Packages and returning errors
    ... The perldoc function guide says about shift (which is ... "Shifts the first value of the array off and returns it, ... If an array of values are passed to a sub, ... Back to my package (which I am currently thinking might be out of my depth, ...
    (comp.lang.perl.misc)
  • Re: Replacing a line
    ... #Using core module Tie::File to process a file in this subroutine ... sub process_one_file { ... $cpp_file = shift; ... for (@array) #Each line should come one by one ...
    (comp.lang.perl.misc)
  • Re: any pointers please? combine words script
    ... ugly but i hate repeated code like that sub has. ... sf> my $source = shift; ... never name a temp, temp. ... sf> return @array; ...
    (comp.lang.perl.misc)
  • Re: Finding nonconsecutive values in array
    ... I want to have the following output when the values in the array are ... for the code given below it only prints the first time ie Current range ... sub printRanges { ... # and then shift until the first two are no longer consecutive ...
    (perl.beginners)