如何编写初始YAML文件?
我有一个哈希%h
,我想将其保存为 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;
但这似乎是一个先有鸡还是先有蛋的问题。
第一次写入yaml文件如何才能被读取?
更新:根据接受的答案是解决方案
#!/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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
DumpFile
,和安装YAML::XS。据我所知,YAML::Syck 被视为已弃用/不受支持。Use
DumpFile
, and install YAML::XS. YAML::Syck is, as far as I know, considered deprecated/unsupported.使用
Dump
将任意对象转换为 YAML 编码的字符串,然后将该字符串打印到文件中。Use
Dump
to convert an arbitrary object to a YAML-encoded string, then print that string to a file.