in reply to Re^2: RFC: "assignary" operator ?= :
in thread RFC: "assignary" operator ?= :
What's the use case which justifies extending Perl's codebase for such an exotic feature?
Concise expressiveness. The ternary ? : is a shortcut for a more convoluted simple if/else
my $var; if($cond) { $var = 'this'; } else { $var = 'that'; }
to be written as
my $var = $cond ? 'this' : 'that';
which is one line compared to 5, 6 or 7, depending on indentation style.
We have more of such subtle operators, eg. ||= vs. //=, where the first checks the LHS truthiness, and the second checks the LHS definedness.
Writing
$var = $var ? 'this' : 'that';
just looks and feels as silly as
$value = $value * 5; $next = $next + 1;
instead of
$value *= 5; $next++;
For the same reasons, I like the compound operator x!! so much, because it lets me set up a parameter list based on truthiness of variables:
$result = build_shed( logs => 24, (screws => 120) x!! @screwdrivers, (nails => 360) x!! @hammers, );
Otherwise, I'd had to say:
my %materials = (logs => 24); $materials{screws} = 120 if @screwdrivers; $materiasl{nails} = 360 if @hammers; $result = build_shed(%materials);
While the second variant is one line less, I regard the first variant as much more readable, and I don't have to introduce a temporary hash just for the sake of building function arguments. Note that in the second variant, the hash name is misspelt as materiasl at the 'nails' case, small bug caught by strict, but annoying. So, instead of
$var = $var ? 'this' : 'that';
I'd rather like to see
$var ?= 'this' : 'that';
because it binds the condition to the LHS in the same way as ||= and //= do.
I can hardly imagine a reason to map non-Boolean values to a previously Boolean $var without confusing any maintainer.
Who said that $var was boolean? It could hold any value, and this value is checked for truthiness.
Anyways - de gustibus non est disputandem.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: RFC: "assignary" operator ?= :
by choroba (Cardinal) on Dec 08, 2019 at 20:49 UTC | |
by shmem (Chancellor) on Dec 08, 2019 at 21:03 UTC | |
Re^4: RFC: "assignary" operator ?= :
by LanX (Saint) on Dec 08, 2019 at 18:42 UTC | |
by shmem (Chancellor) on Dec 08, 2019 at 20:31 UTC | |
by dave_the_m (Monsignor) on Dec 09, 2019 at 22:32 UTC | |
by LanX (Saint) on Dec 09, 2019 at 23:49 UTC | |
by shmem (Chancellor) on Dec 10, 2019 at 11:19 UTC | |
by ikegami (Patriarch) on Dec 10, 2019 at 20:46 UTC | |
by LanX (Saint) on Dec 10, 2019 at 11:58 UTC | |
| |
by Anonymous Monk on Dec 09, 2019 at 01:53 UTC | |
by tobyink (Canon) on Dec 09, 2019 at 13:49 UTC |