Skip to content

Instantly share code, notes, and snippets.

@hshimamoto
Created December 9, 2012 16:15
Show Gist options
  • Save hshimamoto/4245850 to your computer and use it in GitHub Desktop.
Save hshimamoto/4245850 to your computer and use it in GitHub Desktop.
Parse key={p1,p2}
#!/usr/bin/env perl
# vim:set sw=2 sts=2:
# parse
# key = params
# KEY = { P1, P2, {P3} }
sub parse_param {
my $param = shift;
my $s = '';
my $out = '';
foreach my $c (split(//, $param)) {
if ($s eq '') {
if ($c eq '{') {
$out .= '[';
} elsif ($c eq '}') {
$out .= ']';
} elsif ($c eq '"') {
$s = $c;
} elsif ($c !~ /\s/) {
$out .= $c;
}
} else {
$s .= $c;
if ($c eq '"') {
$out .= $s;
$s = '';
}
}
}
return $out;
}
sub parse {
my ($line) = @_;
my $key = '';
my $val = '';
if ($line =~ /^\s*(\S+)\s*=\s*(.+)$/) {
$key = $1;
$val = &parse_param($2);
}
return "{'" . $key . "':" . $val . "}";
}
print &parse('KEY={P1,P2, {P3, {P4}, P5, "P6 {X Y Z}"}, P7}');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment