[tpm] Is there a three-way version of...

John Macdonald john at perlwolf.com
Mon Jun 1 10:02:45 PDT 2009


On Sat, May 30, 2009 at 02:30:37PM -0400, Shaun Fryer wrote:
> >>        The "||", "//" and "&&" operators return the last value evaluated
> >>        (unlike C’s "||" and "&&", which return 0 or 1).
> 
> >    $foo = $opt{foo} || $ENV{PROG_FOO} || $rc_opts{foo} || 'default';
> 
> This is interesting. I learned something new. Now I'm personally
> curious if there's an operator that instead of doing "or equals", does
> "equals or". For instance, I find myself doing this alot (particularly
> in accessors/setters)...
> 
> $x = $y if defined $y;
> 
> What would be helpful is to be able to do this instead.
> 
> $x =|| $y;
> 
> Or even better...
> 
> $x =// $y;

Not in perl5.

Perl6 has a meta-operator R which turns the following binary
operator to take its operands in reverse order.  So:

    $a R- $b
    $b - $a

produce the same result.  You can use this, for example, to provide
Rcmp to sort to get a reversed order string sort.  Perl6 has a number
of things that deal with operators (the way sort takes an operator as
an argument), so the Rop is useful in many of these functional
composition uses.

I've pretty sure that this is still valid for assignment operators,
so just as:

    $x //= $y;

is the same as:

    $x = $x // $y;

but without computing $x twice, you also get:

    $x R//= $y;

to mean:

    $x = $x R// $y;  # i.e. $x = $y // $x;

but again, without rewriting or recomputing $x.


More information about the toronto-pm mailing list