======================================== From ;'([ 1, 2, "([", 0, ([ "internal", "})", 0,({ "key1": "value", "key2": ([ "value", "array", ]), }), }), "end", ])' $VAR1 = [ '1', '2', '([', '0', [ 'internal', '})', '0', { 'key1' => 'value', 'key2' => [ 'value', 'array' ] } ], 'end' ]; #### #! perl -slw use strict; use Data::Dumper; my $re_terminate= qr[ \s* (?: : | , | $ ) ]x; my $re_content = qr[ \( ( [\[\{] ) (.+) [\]\}]\) $re_terminate ]x; my $re_ctt = qr[ \s* \( (.+) \) ]x; my $re_qq = qr' " ( [^"]+ ) " 'x; my $re_csv = qr[ \G \s* (?: $re_qq | $re_ctt | ( [^\s:,]+? ) ) $re_terminate ]x; sub build_structure{ my (@bits, $reftype); $_[0] =~ s[$re_content] [ $reftype = $1; my ($content) = $2 =~ m[^ \s* (.+?) ,? \s* $]x; while( $content =~ m[$re_csv]gc ) { my $chunk = $1||$3||$2||'0'; push @bits, $chunk =~ m|^[\[\{].+[\]\}]| ? build_structure( "($chunk)" ) : $chunk } ]ecg; return $reftype eq '[' ? \@bits : {@bits}; } while( ) { chomp; print '=' x 40, "\nFrom ;'$_'\n"; my $ref = build_structure $_; print Dumper $ref; } __DATA__ ([ "value", "array", ]) ([ 1, 2, "three", 0, ([ "internal", "array", 0, ]), "end", ]) ({ "key1": "value", "key2": "value2" }) ({ "key1": "value", "key2": "value2", "key3": ({ "key1": "value", "key2": "value2" }), }) ([ 1, 2, "([", 0, ([ "internal", "})", 0,({ "key1": "value", "key2": ([ "value", "array", ]), }), }), "end", ])