There are two types of alternation in Raku's regex: the |
and ||
. What is the difference ?
say 'foobar' ~~ / foo || foobar / # 「foo」
say 'foobar' ~~ / foo | foobar / # 「foobar」
A single pipe (|) is the bitwise OR operator. Two pipes (||) is the logical OR operator. They are not interchangeable.
The | operator evaluates both operands even if the left-hand operand evaluates to true, so that the operation result is true regardless of the value of the right-hand operand. The conditional logical OR operator ||, also known as the "short−circuiting" logical OR operator, computes the logical OR of its operands.
The double pipe || is shortcut OR. It means that if the first is true, then the operation will automatically quit, because one condition is already true. Therefore, OR must be true.
To expand on dcp's explanation slightly, in Java a single pipe, | , is what is called a 'Bitwise OR'. That means that it performs a low level OR on the actual bits that make up the arguments. In this case, 3 is 0011 and 4 is 0100 (least 4 significant bits shown).
The || is the old alternation behaviour: try alternation from the first declared to the last
The | try alternation from the longest to the shortest declarative atom. It is called the Longest Token Matching Spec strategy.
say 'foobar' ~~ / foo || foobar / # 「foo」 is the first declared
say 'foobar' ~~ / foo | foobar / # 「foobar」 is the longest token
More detailed answer in this post
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With