Thread [YAML::PP] Include von YAML welches nicht aus Datei kommt (6 answers)
Opened by barney at 2023-11-03 18:19

pq
 2023-11-07 00:24
#195432 #195432
User since
2003-08-04
12208 Artikel
Admin1
[Homepage]
user image
Hier habe ich mal was zusammengebaut.
Dass das snippet mit der id 42 gleichzeitig section 42 und 43 beinhaltet, hat mich etwas verwirrt, aber wie das vom Prinzip her funktoniert, wird hoffentlich klar.
Man ordnet den tags !load-snippets und section jeweils code zu, der dann ausgeführt wird und zum einen etwas zurückliefern kann oder auch Daten im Script verändern kann.

Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;

package snippets {

    my $ypp = YAML::PP->new;
    my $database = {
        42 => <<~'EOM',
            section_42:
                key1: val1
                key2: val2
            section_43:
                key1: val11
                key2: val22
            EOM
        52 => {
        },
    };

    sub load_snippet {
        my ($id) = @_;
        my $yaml = $database->{ $id };
    }

};

package main {
    use YAML::PP;
    my $ypp = YAML::PP->new;
    my $schema = $ypp->schema;
    my %sections;
    $schema->add_resolver(
        tag => "!load-snippets",
        match => [ all => => sub {
            my ($constructor, $event) = @_;
            # load YAML from "database"
            my $yaml = snippets::load_snippet($event->{value});
            my $ypp = YAML::PP->new;
            my $data = $ypp->load_string($yaml);
            %sections = (%sections, %$data);
            return 'placeholder';
        }],
        implicit => 0,
    );
    $schema->add_resolver(
        tag => "!section",
        match => [ all => sub {
            my ($constructor, $event) = @_;
            my $value = $event->{value};
            return $sections{ $value };
        }],
        implicit => 0,
    );

    my ($filename) = @ARGV;
    my $data = $ypp->load_file($filename);
    say $ypp->dump_string($data);
}

Code: (dl )
1
2
3
4
5
6
7
8
# snippets.yaml
---
snippets: !load-snippets 42
workflow:
- s1
- s2
sections:
my_section: !section section_42

Ausgabe:
Code: (dl )
1
2
3
4
5
6
7
8
9
10
% perl snippets.pl snippets.yaml
---
sections:
my_section:
key1: val1
key2: val2
snippets: placeholder
workflow:
- s1
- s2
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. -- Damian Conway in "Perl Best Practices"
lesen: Wiki:Wie frage ich & perlintro Wiki:brian's Leitfaden für jedes Perl-Problem

View full thread [YAML::PP] Include von YAML welches nicht aus Datei kommt