in reply to Parsing Text into Arrays..
#!/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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Parsing Text into Arrays..
by JamesNC (Chaplain) on Jan 20, 2003 at 14:30 UTC |