in reply to split on unescaped delimiters

TIMTOWTDI, A split (with capture) example...
use strict; use warnings; use Data::Dumper; # delimiter is X my $escaped_str = 'Xa\Xdc\\bXc\\\\XdXe'; my @a = (); my $i = 0; foreach (split /(\\.)|X/, $escaped_str) { defined $_ ? do { $a[$i] .= $_ } : do {$i++ } } print Dumper(\@a);

and the output is as expected -
$VAR1 = [ '', 'a\\Xdc\\b', 'c\\\\', 'd', 'e' ];

Replies are listed 'Best First'.
Re: Re: split on unescaped delimiters
by ysth (Canon) on Jan 08, 2004 at 12:24 UTC
    I like that. Trying to come up with a map() version, but
    my $scratch = ''; my @a = (map(defined() ? ($scratch.=$_)[()] : substr($scratch,0,length($scratch),''), split /(\\.)|X/, $escaped_str), length($scratch) ? $scratch : ());
    is the best I can do. And that's way too ugly.

    Maybe something based on @a = @{List::Util::reduce { ... } [], split... };

Re^2: split on unescaped delimiters
by jdeguest (Beadle) on May 27, 2019 at 02:27 UTC
    Thank you for this nice innovative approach. One detail: do not forget -1 as the 3rd parameter to split or else empty values will be discarded as explained in perlfunc for split.