Multisplit: Difference between revisions
Content added Content deleted
(D: fix sample data) |
(→{{header|Perl 6}}: add Perl 6 entry) |
||
Line 138: | Line 138: | ||
└───┴───┴─┘</lang> |
└───┴───┴─┘</lang> |
||
=={{header|Perl 6}}== |
|||
<lang perl6>sub multisplit($str, @seps) { $str.split(/ ||@seps /, :all) } |
|||
my @chunks = multisplit( 'a!===b=!=c==d', < == != = > ); |
|||
# Print the strings. |
|||
say @chunks».Str.perl; |
|||
# Print the positions of the separators. |
|||
for grep Match, @chunks -> $s { |
|||
say " $s from $s.from() to $s.to()"; |
|||
}</lang> |
|||
Output: |
|||
<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). |
|||
As it happens, with the task's specified list of separators, it doesn't make any difference. |
|||
<p> |
|||
Perl 6 automatically returns Match objects that will stringify to the matched pattern, but can also be interrogated for their match positions, as illustrated above by post-processing the results two different ways. |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
<lang PicoLisp>(de multisplit (Str Sep) |
<lang PicoLisp>(de multisplit (Str Sep) |