On Fri, May 14, 2010 at 7:26 AM, Tom <tom.ash...@gmail.com> wrote:
> On Fri, May 07, 2010 at 12:44:01PM -0400, Bob McConnell wrote:
>> From: Tom
>>
>> > I'm having trouble merging YAML streams.
>> >
>> > Basic premise is that I load multiple YAML files and I want to combine
>> > the result. There may be common elements within subsequent YAML files
>> > and I would want the last loaded to be the taken value if one already
>> > existed.
>> >
>> > I have tried treating the YAML nodes like hashes:
>> > eg $yaml = ($yaml1, $yaml2)
>> > but this does not merge them.
>> > Also there may be more than 2 streams, but I would like to cascade
>> > merge them as I loop through a list of YAML files to load (eg
>> > $yaml=($yaml, $next_yaml)) but this gives me a void context.
>> >
>> > Can anyone suggest how I could merge them?
<snip>
> This is some experimental code I am trying to create a sub from:
>
> -------------------- CODE --------------------
> #!/usr/bin/perl
> use YAML::Syck;
> use Data::Dumper;
>
> my ($yaml) = Load(<<'...');
> ---
> nameserver:
>  - 172.23.0.5
>  - 172.23.0.6
> randomvar:
>  - elastic
>  - orange
>  - clint
> network:
>  - eth0:
>    - ip: 192.168.7.2
>    - netmask: 255.255.255.0
> ...
> #print "yaml: \n", Dump($yaml);
>
>
> my ($yaml2) = Load(<<'...');
> ---
> nameserver:
>  - 192.168.0.1
>  - 192.168.0.2
> #network:
> #  - eth0:
> #    - ip: 172.23.10.141
> #    - netmask: 255.255.240.0
> ...
> #print "yaml2: \n", Dump($yaml2);
<snip>

How are you defining "merge," here? What is your desired result?

Are you expecting to have a separate node for each nameserver? Or is
your desired end state a single stream with a singe "nameserver" node
that has all the ips?

The first option is pretty simple:

    my $merged = {NS1 => $yaml1, NS2 => $yaml2};
    print Dump($merged);

Your original code was close, but $yaml = ($yaml1, $yaml2) is not a
valid hashref; it just copies $yaml1 to $yaml and discards $yaml2.
If you had turned on warnings you would have caught the error.
*Always* 'use warnings' at the top of your code.

If your goal is some sort of deeper merge, though, you'll need to
decide what rule you want to use to resolve conflicts, etc.
Hash::Merge from CPAN might be a good place to start.

HTH,

-- j
--------------------------------------------------
This email and attachment(s): [  ] blogable; [ x ] ask first; [  ]
private and confidential

daggerquill [at] gmail [dot] com
http://www.tuaw.com  http://www.downloadsquad.com  http://www.engatiki.org

values of β will give rise to dom!

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to