After some thought, I came up with this not recursive but iterative version, which seems to work... It uses the m//gc and \G regex functionality to walk through the source string... I like this solution, and it should be easily adjusted to use any delimeter...

#!/usr/bin/perl -w use strict; ($\,$,)=("\n","\t"); use Data::Dumper; my $string = '({ 1, 2, "three", 0, ({ "internal", "array", 0, }) "end", })'; my @array = parse($string); print Dumper \@array; sub parse { my $source = shift; my @result = (); my @stack = (\@result); { if($source=~/\G[\s,]*/gc) # skip whitespace { redo; } if($source=~/\G\(\{/gc) # start of a new part { push @stack,[]; redo; } my $part; if($source=~/\G\}\)/gc) # this part is done { $part = pop @stack; } elsif ($source=~/\G"(.*?)"/gc) # quoted string { $part = $1 } elsif ($source=~/\G(\d+)/gc) # unquoted decimal { $part=$1; } elsif (pos($source)==length($source)) # done { last; } else { # something alien die "I don't get it at '". substr($source,pos($source))."'" } my $target = $stack[$#stack]; # where to add part push @{$target},$part; # add it! redo; } return @result; }

Update: JamesNC is da man... And I have thick fingers


In reply to Re: Parsing Text into Arrays.. by Gilimanjaro
in thread Parsing Text into Arrays.. by castaway

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.