Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Parsing Text into Arrays..

by Gilimanjaro (Hermit)
on Jan 20, 2003 at 13:46 UTC ( [id://228341]=note: print w/replies, xml ) Need Help??


in reply to Parsing Text into Arrays..

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

Replies are listed 'Best First'.
Re: Re: Parsing Text into Arrays..
by JamesNC (Chaplain) on Jan 20, 2003 at 14:30 UTC
    typo at line:37 is->  push @($target},$part;           # add it! needs a left curly-fry..mmm  push @{$target},$part;           # add it!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://228341]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-04-19 23:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found