in reply to Operator overloading with returning lists?

I want to overload an operator (ideally '~~') but want the result to be a list. It seems like that's not possible, the list is only handled like in scalar context.
Indeed. There were some messages on p5p about this quite recently. I think the outcome was "No, that's not possible. The implementor (Ilya) of overloading deemed it not necessary to be able to ask the context - that is, the operands are always in scalar context".

Note that when overloading was implemented, '~~' wasn't an operator, and only a few overloadable operators would behave differently in list context anyway. (<> being the obvious on. x behaves different in list context as well, but only if its LHS has parens, making it an odd one).

  • Comment on Re: Operator overloading with returning lists?

Replies are listed 'Best First'.
Re^2: Operator overloading with returning lists?
by ikegami (Patriarch) on Nov 27, 2008 at 23:09 UTC

    x behaves different in list context as well

    Not a very good example. It's more the LHS operand than the context which determines what is returned.

    >perl -le"$x = 'x' x 5; print $x" xxxxx >perl -le"$x = ( 'x' x 5 )[0]; print $x" xxxxx >perl -le"$x = ( ('x') x 5 )[0]; print $x" x

    The only time context matters, x behaves normally.

    >perl -le"$x = ('x') x 5; print $x" xxxxx
      x behaves different in list context as well
      Not a very good example. It's more the LHS operand than the context which determines what is returned.
      That's not all I said. I immediately followed it (not even stopping to start a new sentence) with
      but only if its LHS has parens, making it an odd one
      Both context and the LHS matter, just as I said:
      my $w = 'x' x 5; say "$w"; # Scalar context, no parens. my $x = ('x') x 5; say "$x"; # Scalar context, parens. my @y = 'x' x 5; say "@y"; # List context, no parens. my @z = ('x') x 5; say "@z"; # List context, parens. __END__ xxxxx xxxxx xxxxx x x x x x
        since when does scalar context of a list result in a join???
        DB<88> p Dumper (('x') x 5) $VAR1 = 'x'; $VAR2 = 'x'; $VAR3 = 'x'; $VAR4 = 'x'; $VAR5 = 'x'; DB<89> p Dumper scalar (('x') x 5) $VAR1 = 'xxxxx'; DB<90> p Dumper scalar (@x=('x') x 5) $VAR1 = 5; DB<91> p Dumper (scalar qw/x x x x x/) $VAR1 = 'x';

        mysterious perl ... 8(

        Cheers Rolf

        UPDATE:

        DB<97> p Dumper scalar ( (1,2) x 5 ) $VAR1 = '22222'; DB<98> p Dumper ( (1,2) x 5 ) $VAR1 = 1; $VAR2 = 2; $VAR3 = 1; $VAR4 = 2; $VAR5 = 1; $VAR6 = 2; $VAR7 = 1; $VAR8 = 2; $VAR9 = 1; $VAR10 = 2;

        The scalar is applied to the list before the x-op can act. The parens are ignored...

        Thats a bug or a feature?