in reply to Re: parse lisp style config
in thread parse lisp style config
It's not able to parse string to array.#!/bin/perl use strict; use warnings; use Data::Dumper; use File::Slurper qw(read_text); sub parse_nested_brackets { my ($string) = @_; my $index = 0; return parse_nested_brackets_recursive($string, \$index); } sub parse_nested_brackets_recursive { my ($string, $index_ref) = @_; my %hash; my ($key, $value); while ($$index_ref < length($string)) { my $char = substr($string, $$index_ref, 1); $$index_ref++; if ($char eq '(') { my $nested_hash = parse_nested_brackets_recursive($string, + $index_ref); if (defined $key) { $hash{$key} = $nested_hash; $key = undef; } else { %hash = (%hash, %$nested_hash); } } elsif ($char eq ')') { if (defined $key && defined $value) { $hash{$key} = $value; $key = undef; $value = undef; } return \%hash; } elsif ($char =~ /\s/) { next; } else { if (!defined $key) { $key = $char; } elsif (!defined $value) { $value = $char; } else { $value .= $char; } } } return \%hash; } my $string = read_text shift; my $hash = parse_nested_brackets($string); print Dumper($hash);
|
|---|