P
PeterSShenkin
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;
}
}
====================
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;
}
}
====================