Ramse
Ramse

Reputation: 144

yml files to one

I am planning to merge two yml files to one single yml file using "use Hash::Merge qw( merge );"

Here is my sample script :-

use strict;
use warnings;
use Hash::Merge qw( merge );
use YAML::XS qw(Load Dump);
use File::Slurp qw(read_file write_file append_file);

my $yaml1 = "/home/test/one.yml";
my $yaml2 = "/home/test/two.yml";
my $in_yaml = read_file($yaml1, { binmode => ':raw' });
my $clkgrps = Load $in_yaml ;
my $in_yaml1 = read_file($yaml2, { binmode => ':raw' });
my $clkgrps1 = Load $in_yaml1;
my $clockgroups = merge($clkgrps, $clkgrps1);
my $out_yaml = Dump $clockgroups;
my $outFile = "clockgroups_used.yml" ;
print("Generating Yaml file: $outFile \n") ;
write_file($outFile, { binmode => ':raw' }, $out_yaml);

one.yml:-

emailName: David
emailAddresses:
    - [email protected]
    - [email protected]
credentials:
    username: sillymoose
    password: itsasecret

two.yml:-

 emailName: Pranay
emailAddresses:
    - [email protected]
    - [email protected]
credentials:
    username: link
    password: sanity

After executing my script i do see the output of final yml file clockgroups_used.yml has following content which is only the content from one.yml

    ---
credentials:
  password: itsasecret
  username: sillymoose
emailAddresses:
- [email protected]
- [email protected]
- [email protected]
- [email protected]
emailName: David

Am I doing anything wrong here? Why i am not able to see merge of two yml files?

Upvotes: 1

Views: 169

Answers (1)

Dada
Dada

Reputation: 6626

After loading the Hash::Merge module, add this line:

Hash::Merge::set_behavior('RETAINMENT_PRECEDENT');

The default behavior of Hash::Merge is to not change the datatypes of the elements within the hashes, and to prioritize the content of the first argument of merge. Setting RETAINMENT_PRECEDENT instructs Hash::Merge to keep all data of both hashes by creating arrays if necessary.

The resulting YAML file is thus

---
credentials:
  password:
  - itsasecret
  - sanity
  username:
  - sillymoose
  - link
emailAddresses:
- [email protected]
- [email protected]
- [email protected]
- [email protected]
emailName:
- David
- Pranay

Upvotes: 1

Related Questions