jo37 has asked for the wisdom of the Perl Monks concerning the following question:
Recently I played with the logical/defined or in a scenario where the result should be an lvalue. For the defined or (//) the documentation clearly states that the result is not an lvalue. While this is not mentioned for the logical or (||), it holds there too.
I don't know the reason for this behaviour, but it prevents the usage of these operators as a substitute for the non-existing (binary) "Elvis operator" (?:), where X ?: Z would act like X ? X : Z, without evaluating X twice.
To my surprise I realized that dereferencing a reference to the result of an or operator provides an lvalue, given the operands are lvalues.
That is, the following expression does compile and works: ${\(X // Y)}++.
I could not find anything in the documentation that would forbid such a usage.
So my questions are:
Here is a complete example:
#!/usr/bin/perl use v5.24; use warnings; use experimental 'signatures'; say "This is perl $]"; sub f :lvalue ($k) { state $href = {a => 10}; $href->{$k}; } sub g :lvalue ($k) { state $href = {b => 20}; $href->{$k}; } eval q{ (f($_) || g($_))++ for qw(a b); 1; } or warn $@; ${\(f($_) // g($_))}++ for qw(a b); say "f(a) = ", f('a'); say "g(b) = ", g('b'); __DATA__ Can't modify logical or (||) in postincrement (++) at (eval 5) line 2, + near ")++" This is perl 5.032001 f(a) = 11 g(b) = 21
Greetings,
🐻
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Logical/defined or as lvalue
by hv (Prior) on Sep 03, 2024 at 21:54 UTC | |
by Fletch (Bishop) on Sep 04, 2024 at 03:09 UTC | |
by jo37 (Curate) on Sep 04, 2024 at 08:40 UTC | |
by LanX (Saint) on Sep 03, 2024 at 22:15 UTC | |
by hv (Prior) on Sep 03, 2024 at 21:56 UTC | |
by jdporter (Paladin) on Sep 03, 2024 at 22:17 UTC | |
|
Re: Logical/defined or as lvalue
by LanX (Saint) on Sep 03, 2024 at 19:57 UTC | |
by jo37 (Curate) on Sep 04, 2024 at 16:50 UTC | |
|
Re: Logical/defined or as lvalue
by ikegami (Patriarch) on Sep 03, 2024 at 19:43 UTC | |
by NERDVANA (Priest) on Sep 03, 2024 at 21:13 UTC | |
by LanX (Saint) on Sep 03, 2024 at 21:31 UTC | |
by NERDVANA (Priest) on Sep 04, 2024 at 03:52 UTC | |
by jo37 (Curate) on Sep 04, 2024 at 16:43 UTC | |
by ikegami (Patriarch) on Sep 04, 2024 at 17:00 UTC | |
| |
by ikegami (Patriarch) on Sep 04, 2024 at 16:51 UTC | |
by jo37 (Curate) on Sep 03, 2024 at 20:12 UTC | |
by ikegami (Patriarch) on Sep 03, 2024 at 20:25 UTC | |
by LanX (Saint) on Sep 03, 2024 at 20:45 UTC |