Sandra Schlichting
Sandra Schlichting

Reputation: 25986

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;
}

Upvotes: 2

Views: 5421

Answers (3)

Brad Gilbert
Brad Gilbert

Reputation: 34120

#!/usr/bin/perl
use warnings;
use strict;

use YAML::Any qw'DumpFile LoadFile';

my $data_filename = 'seen.yaml';

my $data = LoadFile( $data_filename );

unless( $data ){
  # first time
  $data = {
    1 => 2
  };
}

$data->{3} = 4;

DumpFile( $data_filename, $h );

Upvotes: 0

Ashley
Ashley

Reputation: 4335

Use DumpFile, and install YAML::XS. YAML::Syck is, as far as I know, considered deprecated/unsupported.

~>perl -MYAML=DumpFile -le 'DumpFile("test.yml", { o => "hai" })'
~>cat test.yml
---
o: hai

Upvotes: 4

mob
mob

Reputation: 118605

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;

Upvotes: 2

Related Questions