in reply to Split Operation
In Chapter 5, page 194, he says: "on the vast majority of systems, you simply can't match arbitrarily nested constructs with regular expressions." There are ways in Perl to do some zoomy things like dynamically create a regex at some depth. But my investigation appears to indicate that this is NOT "just a split" and that figuring out that something like [e, [f, g, h, [i, j], k, l], m, n] is all one thing, is likely to be darn difficult in a single regex, if we assume that we just don't know how deep the nesting levels of [ ] go!
There is a posting with some code that counts left and right brackets to figure out the depth. Do NOT assume that more lines is slower! Something is weird in my browser now and I can't look again at that code easily at the moment, but I suspect that it is likely to be (or something very similar to it) to be the fastest thing going. Either that or this "balanced" module that was also suggested.
I'm just saying that if J. Friedl says this problem is hard, I'm unlikely at my skill level to arrive at a "simple" solution that proves him wrong.
here is my effort at some code - I can't do it with one regex:
#!/usr/bin/perl -w use strict; my $test="xyz,[a,b],c,'d',[e,[f,g,h,[i,j],k,l],m,n],o,p"; my @test = $test =~ m/,|[\w']+|[\[\]]/g; my @result; while (@test) { my $t = shift @test; if ($t =~ /[\w']+/) { push (@result, $t); } #simple "word" thing elsif ($t =~ /\[/) #complex bracketed expression { push (@result, bracket_exp()); } # commas are skipped.. } sub bracket_exp { my $temp ="["; my $depth = 1; while ($depth) { my $next_thing = shift @test; $temp .= $next_thing; $depth++ if $next_thing eq '['; $depth-- if $next_thing eq ']'; } return ($temp); } foreach my $t ( @result) { print "$t\n"; } __END__ prints: xyz [a,b] c 'd' [e,[f,g,h,[i,j],k,l],m,n] o p
|
|---|