saintmike has asked for the wisdom of the Perl Monks concerning the following question:
given a textual data structure description, I'd like to set up a nested Perl data structure, consisting of hashes and arrays.
The description looks like this:
and should be transformed into"foo[1].bar.baz[0]", value: 123
$data = { foo => [ undef, { bar => { baz => ['123'] } } ] }
I've come up with a solution (don't ask how long it took :), but I keep wondering: Doesn't there have to be a better way? Sure, you could modify the description a bit and then eval it, but I don't like using eval.
Here's my clunky code:
use Data::Dumper; my $data = str2data('foo[1].bar.baz[0]', 123); print Dumper($data), "\n"; sub str2data { my($string, $value) = @_; my $tmp; my @idxs = (); for my $part (split /\./, $string) { if($part =~ /(.*?)\[(.*?)\]/) { push @idxs, $1, $2; } else { push @idxs, $part; } } while(defined(my $idx = pop @idxs)) { if($idx =~ /^\d+$/) { $tmp = []; $tmp->[$idx] = $value; $value = $tmp; } else { $tmp = {}; $tmp->{$idx} = $value; $value = $tmp; } } return $value; }
Can you do better?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Construct a data structure from a string
by BrowserUk (Patriarch) on Sep 23, 2004 at 02:57 UTC | |
|
Re: Construct a data structure from a string
by jweed (Chaplain) on Sep 23, 2004 at 03:26 UTC | |
|
Re: Construct a data structure from a string
by dws (Chancellor) on Sep 23, 2004 at 03:33 UTC | |
|
Re: Construct a data structure from a string
by nobull (Friar) on Sep 23, 2004 at 06:39 UTC | |
by nobull (Friar) on Sep 23, 2004 at 07:59 UTC | |
|
Re: Construct a data structure from a string
by alftheo (Scribe) on Sep 23, 2004 at 10:53 UTC | |
|
Re: Construct a data structure from a string
by TedPride (Priest) on Sep 23, 2004 at 08:27 UTC | |
|
Re: Construct a data structure from a string
by water (Deacon) on Sep 24, 2004 at 02:25 UTC |