Skip to content

Commit 20ab419

Browse files
authored
Merge pull request #59 from rabbiveesh/veesh/moar-short-circuit
doc: be explicit about the short-circuiting behavior
2 parents 0b419bb + 6e9684b commit 20ab419

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

ppcs/ppc0021-optional-chaining-operator.md

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,25 @@ is equivalent to:
100100

101101
with the important caveat that EXPR1 is only evaluated once.
102102

103+
When used in a longer chain of dereferences, an undef value will short-circuit the entire
104+
chain, rather than just a single expression:
105+
106+
EXPR1 ?-> EXPR2 ?-> EXPR3
107+
108+
is equivalent to:
109+
110+
```perl
111+
if (defined EXPR1) {
112+
if (defined EXPR1->EXPR2) {
113+
return EXPR1->EXPR2->EXPR3
114+
} else {
115+
return ()
116+
}
117+
} else {
118+
return () # empty list
119+
}
120+
```
121+
103122
## Backwards Compatibility
104123

105124
All code with `?->` currently yields a compile time syntax error, so there
@@ -170,11 +189,8 @@ Expected common uses:
170189
# my $class = 'SomeClass'; $class->new if defined $class;
171190
my $class = 'SomeClass'; $class?->new;
172191

173-
# my $obj = %SomeClass:: ? SomeClass->new : ();
174-
my $obj = SomeClass?->new; # TBD: see 'Future Scope' below.
175-
176-
# my @objs = (%NotValid:: ? NotValid->new : (), %Valid:: ? Valid->new : ());
177-
my @objs = ( NotValid?->new, Valid?->new ); # @objs == ( ValidObject )
192+
# defined $aref ? $aref->[0] = 9001 : ()
193+
$aref?->[0] = 9001; # $aref remains undef in the undef case
178194
```
179195

180196
Unusual and edge cases, for comprehension:

0 commit comments

Comments
 (0)