开发者

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


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


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;


#!/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 );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜