Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

$x | $y | $z = $z | ($x | $y) ?

by perl5ever (Pilgrim)
on Sep 06, 2012 at 15:44 UTC ( #992121=perlquestion: print w/replies, xml ) Need Help??
perl5ever has asked for the wisdom of the Perl Monks concerning the following question:

When playing around with the overload module, I found that perl parses
$x | $y | $z
as if it were
$z | ($x | $y)
I was hoping to a new (left-associative) operation on a new data type (objects of a certain class), so that I could write:
$x | $y | $z
and have it translate to:
where the order of the arguments to f matters, but it doesn't look like I can do that with overloading.

The SO post with more details:

Replies are listed 'Best First'.
Re: $x | $y | $z = $z | ($x | $y) ?
by philiprbrenan (Monk) on Sep 06, 2012 at 16:00 UTC
    use feature ":5.14"; use warnings FATAL => qw(all); use strict; use Data::Dump qw(dump pp); sub foo() {package foo; use overload '|' => \&p; sub p {bless [@{$_[0]},@{$_[1]}]} } my $x = bless ["x"], "foo"; my $y = bless ["y"], "foo"; my $z = bless ["z"], "foo"; my $p = $x | $y | $z; pp($p)


    bless(["x", "y", "z"], "foo")
      Thanks - I see my problem now. My operation wasn't returning a blessed object.
Re: $x | $y | $z = $z | ($x | $y) ?
by ikegami (Pope) on Sep 07, 2012 at 00:06 UTC
    Overloaded operator handlers sometimes receive operands in reversed order, but Perl will notify the handler when it does so by setting the swapped argument to true.


    Three arguments are passed to all subroutines specified in the use overload directive (with one exception - see nomethod). [...] The third argument is set to TRUE if (and only if) the two operands have been swapped. Perl may do this to ensure that the first argument ($self ) is an object implementing the overloaded operation, in line with general object calling conventions. [...]

    You probably disregarded that argument?

Re: $x | $y | $z = $z | ($x | $y) ?
by sundialsvc4 (Abbot) on Sep 06, 2012 at 19:54 UTC

    And ... if I ever saw a statement like $a = $b | $c | $d in source-code, such that the meaning of $a or $b or $c had any possibility of any side-effects, or might possibly have any dependency on left- vs. right-hand precedence ...

    ... or really required any “thought” at all ...

    ... then I certainly would ... forsooth!! ... come after that person with a wet-noodle, because he or she surely has ... forsooth!! ... visited upon me an unholy maintenance nightmare.

    Please, be kind to me, the programmer who is trying to deal with your code five years after you got smooshed by that taxi.   Please do not be “clever.”


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://992121]
Front-paged by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2018-04-24 09:36 GMT
Find Nodes?
    Voting Booth?