Skip to content

Instantly share code, notes, and snippets.

@maxhq
Created September 21, 2021 09:45
Show Gist options
  • Save maxhq/3b368c7467941d139aa7fc7a7446b647 to your computer and use it in GitHub Desktop.
Save maxhq/3b368c7467941d139aa7fc7a7446b647 to your computer and use it in GitHub Desktop.
Perl YAML parser embedded in Bash
#!/usr/bin/env bash
set -e
function parse_yaml {
local source="$1"
local prefix="$2"
cat "$source" | perl -MCPAN::Meta::YAML <(cat <<'EOF'
$yaml_str = do { local $/; <STDIN> };
$yaml = CPAN::Meta::YAML->read_string($yaml_str) or die CPAN::Meta::YAML->errstr;
@check = ( { val => $yaml->[0], pre => '' } );
while (my $check = shift @check) {
if (ref $check->{val} eq 'ARRAY') {
my $i;
unshift @check, map { { val => $_, pre => $check->{pre}.'_'.$i++ } } @{$check->{val}};
next;
}
if (ref $check->{val} eq 'HASH') {
unshift @check, map { { val => $check->{val}->{$_}, pre => $check->{pre}.'_'.$_ } } sort keys %{$check->{val}};
next;
}
$check->{pre} =~ s/-/_/g;
printf "%s=\"%s\"\n", $check->{pre}, $check->{val};
}
EOF
) | perl -pe "s/^/$prefix/"
}
parse_yaml "test.yaml" "CONF_"
top1:
ei-ns:
- aa
- bb
zwei: cc
top2: dd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment