in reply to Construct a data structure from a string

This is just a slightly more complex version of the "convert a list to a hierachical hash subscript" question.
use strict; use warnings; use Data::Dumper; my $data = str2data('foo[1].bar.baz[0]', 123); print Dumper($data), "\n"; sub str2data { my($string, $value) = @_; my $r = \my $return; $r = $1 ? \$$r->{$1} : \$$r->[$2] while $string =~ /\G(?:\.?(\w+)|\[(\d+)\])/g; $$r = $value; $return; }
Note - I'm assuming that the input is known to be valid and that $1 can never be '0'. If $1 could ever be '0' then insert 'defined' in the obvious place.

Replies are listed 'Best First'.
Re^2: Construct a data structure from a string
by nobull (Friar) on Sep 23, 2004 at 07:59 UTC
    $r = $1 ? \$$r->{$1} : \$$r->[$2] while $string =~ /\G(?:\.?(\w+)|\[(\d+)\])/g;

    Note - I'm assuming that the input is known to be valid and that $1 can never be '0'.

    Given I'm already assuming $string is well formed the regex is much more complex than it needs to be.

    $r = $1 ? \$$r->{$1} : \$$r->[$2] while $string =~ /(\w+)|\[(\d+)/g;