Search code examples
perlhashyaml

How to write the initial YAML file?


I have a hash %h which I would like to save as YAML.

#!/usr/bin/perl

use warnings;
use strict;

my %h = ();

# -----

use YAML::Syck;
my $y = YAML::Syck::LoadFile('have_seen.yaml');

$y->%h ???

my $yaml = YAML::Syck::Dump($y);
$yaml::Syck::ImplicitUnicode = 1;

open F, ">have_seen.yaml" or die $!;
print F $yaml . "---\n";
close F;

But it seams like a chicken and egg problem.

How do I write the yaml file for the first time, so it can be read?

Update: Based on the accepted answer was the solution

#!/usr/bin/perl

use warnings;
use strict;
use YAML::Syck;
use Data::Dumper;

my $first_time = 1;

if ($first_time) {

    my %h = ("1" => 2);

    open F, '>', 'seen.yaml';
    print F YAML::Syck::Dump(\%h);
    close F;

} else {

    my $h = YAML::Syck::LoadFile('seen.yaml');

    $h->{"3"} = 4;

    print Dumper $h;

    my $yaml = YAML::Syck::Dump($h);
    $yaml::Syck::ImplicitUnicode = 1;

    open F, ">seen.yaml" or die $!;
    print F $yaml . "---\n";
    close F;
}

Solution

  • Use Dump to convert an arbitrary object to a YAML-encoded string, then print that string to a file.

    $h{foo} = "bar";
    $h{"answer to life, the universe, and everything"} = 42;
    
    open F, '>', 'have_seen.yaml';
    print F YAML::Syck::Dump( \%h );
    close F;