Perl has several of what i tend to think of as 'convenience operators'.
Perhaps the best example of this is $var ||= 100; which is shorthand for $var = 100 unless $var; or even if( not $var ) { $var = 100; }
In Perl 6, this has been further improved to //= which (I think) distinguishes between undef and 0 or ''.
The are also all the op= shorthands += , ^=, .= etc.
We also have the ternary operator ? : ; which is often used in expressions like
my $smallest = 1e308; $smallest = $smallest < $_ ? $smallest : $_ for @array;
which is great, but suffers from requiring both terms to be evaluated twice, which besides going against Laziness, also means that if one of the terms is a function, then the function is called twice. And if the value of the function can change between calls: eg.
# Not a good example, but demonstrates the point $latest = $latest > time() ? $latest : time();
probably isn't quite right. Or if the function has side effects, then you are forced to use a temp variable
# This would be the same as a straight assignment, but '!=' is just a +placeholder for a.n. other comparison operation. my $temp = function_with_side_effects(); $state = $state != $temp ? $temp : $state;
I wonder if there would be any utility in having a short-cut operator for the general cases where the ternary is a conditional assignment with only two terms involved?
my $smallest = 1e308; $smallest ?<:= $_ for @array; $latest ?>:= time;
These conditional assignment operators would read as
"If the current value of the lvalue is <op>* than the rvalue, then assign the rvalue to the lvalue"
* <op> is one of these infix binary comparison operators: <, <=, >, >=, lt, le, gt, ge.
Eg.
$lvalue ?<:= $rvalue; $lvalue ?>:= $rvalue; $lvalue ?<=:= $rvalue; $lvalue ?>=:= $rvalue; $lvalue ?lt:= $rvalue; $lvalue ?gt:= $rvalue; $lvalue ?ge:= $rvalue; $lvalue ?le:= $rvalue;
There are likely some reasons why my suggested syntax wouldn't be feasable to implement in the the perl 5 parser, but maybe in perl 6?
Does this idea have any merit? Would anyone but me use it?
Finally, is it possible to invent new operators using overload? Or would you have to resort to source filters to implement this outside of the core?
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |