in reply to Thoughts on some new operators for perl (6 or 7)
It seems to me that if it were pursued, you'd want a general conditional assignment operator. I chose ?= for notation because I don't think it conflicts with any existing syntax, and it has some intuitive appeal to me, because of the resemblance to, e.g., ||=. Follow it with a comparison operator and the value to compare. If the comparison is true, do the assignment:
The PerlMonk tr/// Advocate
The last isn't quite equivalent to $foo ||= $bar, for cases where $foo and $bar are different values of false. ||= would do the assignment; ?= would not.# syntax lvalue ?= op value; # ex: $lowest = $_ if $lowest > $_; $lowest ?= > $_; # ex: $highest = substr($_, 10, 5) if $highest lt substr($_, 10, 5) $highest ?= lt substr($_, 10, 5); # ex: $foo ||= $bar, using the generalized ?= operator $foo ?= || $bar;
Unary tests could work, if Perl understands that unary operators operate on the lvalue, and I think in that case that ! should be combinable with other ops, since we already have $a ||= $b to denote $a = $b if !$a:
That's not going to win any converts from //= notation, and there's not much clamor for exists-based-defaulting, but it did seem a logical extension.# ex: $foo = $default if !defined($foo) $foo ?= !defined $default; # ex: $foo{'bar'} = $default if exists($foo{'bar'}) # That is, we're resetting the value, but not creating it $foo{'bar'} ?= exists $default;
Update: extending a little further, we could make unary operators into mutators by making the value optional. If no value is given, the result of the (unary) operation is assigned back to the lvalue:
Operators that can be unary or binary present a syntactic problem. What is meant by# $foo = uc($foo) $foo ?= uc; # even do arrays! @arr ?= reverse;
? I think assuming binary operators in those cases make sense, while in the unambiguous case of no argument, you could negate a value with minimal typing:# $foo = 5 if -$foo? # $foo = $foo - 5 if $foo - 5? $foo ?= - 5;
$foo{$bar}{$baz} ?= -;
The PerlMonk tr/// Advocate
|
---|
In Section
Meditations