Multisplit: Difference between revisions

m
→‎{{header|Raku}}: fewer parens, nicer output formatting
m (→‎{{header|J}}: clearer result format)
m (→‎{{header|Raku}}: fewer parens, nicer output formatting)
Line 1,719:
=={{header|Raku}}==
(formerly Perl 6)
<lang perl6>sub multisplit($str, @seps) { $str.split(: / ||@seps /, :v) }
{{works with|Rakudo|2020.08.1}}
<lang perl6>sub multisplit($str, @seps) { $str.split(/ ||@seps /, :v) }
 
my @chunks = multisplit( 'a!===b=!=c==d', < == != = > );
 
# Print the strings.
Line 1,729 ⟶ 1,728:
# Print the positions of the separators.
for grep Match, @chunks -> $s {
say " {$s.fmt: '%2s'} from {$s.from().fmt: '%2d'} to {$s.to().fmt: '%2d'}";
}</lang>
{{out}}
<pre>("a", "!=", "", "==", "b", "=", "", "!=", "c", "==", "d")
!= from 1 to 3
== from 3 to 5
= from 6 to 7
!= from 7 to 9
== from 10 to 12</pre>
Using the array <tt>@seps</tt> in a pattern automatically does alternation.
By default this would do longest-term matching (that is, <tt>|</tt> semantics), but we can force it to do left-to-right matching by embedding the array in a short-circuit alternation (that is, <tt>||</tt> semantics).
2,392

edits